1、排序
result = result.stream().sorted(Comparator.comparing(QueryRecordListVO::getUseTime,Comparator.nullsFirst(String::compareTo)).reversed()).collect(Collectors.toList()); //倒序
result = result.stream().sorted(Comparator.comparing(QueryRecordListVO::getUseTime,Comparator.nullsLast(String::compareTo))).collect(Collectors.toList());
2、将对象集合转成String集合
List<String> ids = accounts.stream().map(Account::getId).collect(Collectors.toList());
List<String> ids = accounts.stream().map(t -> t.getId).collect(Collectors.toList());
3、获取对象中level==1的数据
List<Group> minGroup = userGroup.stream().filter(t -> t.getLevel().equals("1")).collect(Collectors.toList());
4、把list集合换成map
Map<BigDecimal, TariffConfig> configMap = tempList.stream().collect(Collectors.toMap(TariffConfig::getMinValue, Function.identity()));
5、根据name,sex两个属性去重
List<GoodsPrice> unique = goodsPrices.stream().collect(
Collectors.collectingAndThen(
Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.getGoodsVersion() + ";" + o.getPeriod()))), ArrayList::new)
);
6、分组 通过groupingBy分组指定字段
list.stream().collect(Collectors.groupingBy(User::getSex));
7、过滤
list.stream().filter(a -> !a.getJobNumber().equals("201901")).collect(Collectors.toList());
8、求和
基本类型:先mapToInt,然后调用sum方法
List.stream().mapToInt(User::getAge).sum();
大数类型:reduce调用BigDecimal::add方法
List.stream().map(User::getFamilyMemberQuantity).reduce(BigDecimal.ZERO, BigDecimal::add);
9、最值
最大值
List.stream().map(User::getEntryDate).max(Date::compareTo).get();
最小值
List.stream().map(User::getEntryDate).min(Date::compareTo).get();
10、去重
List.stream().distinct().collect(Collectors.toList());
11、循环设置值
checkCodeRecords.stream().forEach(o ->{
o.setIsMain(0);
});
12、修改对象中的属性值,赋给新的集合
List<User> copyUsers = students.stream().map(s ->
{
User user = new User();
user.setUid(s.getId());
user.setUname(s.getName());
return user;
}
).collect(Collectors.toList());
本文介绍了Java1.8 Stream流的常见操作,包括排序、对象集合到String集合的转换、筛选level为1的对象、转换为Map、按特定属性去重、分组、过滤、求和、找出最大值和最小值、去重、循环设置值以及修改对象属性并创建新集合等实战技巧。
443

被折叠的 条评论
为什么被折叠?



