lambda

发布于:2022-12-17 ⋅ 阅读:(560) ⋅ 点赞:(0)

Lambda

排序

1.单字段排序,根据id排序
userList.sort(Comparator.comparing(User::getId));
2.多字段排序,根据id,年龄排序
userList.sort(Comparator.comparing(User::getId).thenComparing(User::getAge));

list转map

Map<Long, User> userMap = userList.stream().collect(Collectors.toMap(User::getId, a -> a,(k1,k2)->k1))

求最小对象 min、max

Comparator comparator = Comparator.comparing(User::getAge);
User user = userList.stream().min(comparator).get();

判断字段为空

stream.filter(x -> x.getDateTime()!=null)

过滤

List userCommonList = userList.stream().filter(a -> !a.getJobNumber().equals(“201901”)).collect(Collectors.toList());

求和

Integer sum = userList.stream().collect(Collectors.summingInt(User::getAge));

去重

List sLists = userList.stream().collect(
Collectors.collectingAndThen(Collectors.toCollection(
() -> new TreeSet<>(Comparator.comparing(c -> c.getAge()))), ArrayList::new));
这种滤重的方法有个缺点,就是获取的list可能每回返回的结果是随机的