Java1.8 Stream流常用操作

本文介绍了Java1.8 Stream流的常见操作,包括排序、对象集合到String集合的转换、筛选level为1的对象、转换为Map、按特定属性去重、分组、过滤、求和、找出最大值和最小值、去重、循环设置值以及修改对象属性并创建新集合等实战技巧。

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());
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值