记录Java8中便捷操作

排序

list排序

正序排序

List<Student> sList = studentList.stream().sorted(Comparator.comparing(Student::getId)).collect(Collectors.toList());

倒序

List<Student> sList = studentList.stream().sorted(Comparator.comparing(Student::getId).reversed()).collect(Collectors.toList());

多个排序条件

List<Student> sList = studentList.stream().sorted(Comparator.comparing(Student::getId).thenComparing(Student::getName)).collect(Collectors.toList());

预防空指针

List<Student> sList = studentList.stream().sorted(Comparator.comparing(Student::getId, Comparator.nullsLast(Comparator.naturalOrder()))).collect(Collectors.toList());

map排序

// toMap()方法是Collections工具包中
// 正序
Map<String, Integer> sorted = map
                .entrySet()
                .stream()
                .sorted(Map.Entry.comparingByValue())
                .collect(toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e2,
                                LinkedHashMap::new));

// 反序
Map<String, Integer> reserveSort= map.entrySet()
	.stream()
	.sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
	.collect(toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e2, LinkedHashMap::new));

去重

list根据某个属性去重

List<Product> products = listedProduct.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Product::getOriginProductId))), ArrayList::new));

分组

简单分组

Map<String, List<P>> groupMap1 = list.stream()
                .collect(Collectors.groupingBy(P::getType));

指定字段分组

Map<String, Set<String>> groupMap2 = list.stream()
                .collect(Collectors.groupingBy(P::getType, Collectors.mapping(P::getName, Collectors.toSet())));

取值

可避免报错:IllegalStateException: Duplicate key xxx,key

Map<Integer, String> map = data.stream().collect(Collectors.toMap(Person::getAge, Person::getName,(value1, value2 )->{ 
            return value2; 
	}));

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值