set.stream使用 java_java 8 stream使用方法总结

1、list单个数据+1

list.stream().forEach(x->{x.age+=1;});

list = list.stream().map(s -> s.setAge(s.getAge() + 1)).collect(Collectors.toList());

2、将某个参数取出重组list

List ids = list.stream().map(LcsReportformGroupEntity::getId).collect(Collectors.toList());

StringmergedString= strings.stream().filter(string-> !string.isEmpty()).collect(Collectors.joining(", ")); System.out.println("合并字符串: "+ mergedString);

可用map 的 x -> { return value}重新定义一个对象

3、过滤掉不符合条件的数据

//查找身高在1.8米及以上的男生

List boys = studentList.stream().filter(s->s.getGender().equals("boy") && s.getHeight() >= 1.8).collect(Collectors.toList());

4、按某个字段排序升序

List result = totalList.stream().sorted(Comparator.comparingLong(TotalBytesHostBean::getTotalBytes)).collect(Collectors.toList());

倒序(降序)

List result = totalList.stream().sorted(Comparator.comparingLong(TotalBytesHostBean::getTotalBytes).reversed()).collect(Collectors.toList());

多个字段排序

List userList3 = userList.stream() .sorted(Comparator.comparing(userInfo::getAge).thenComparing(userInfo::getMoney)) .collect(Collectors.toList());

多字段正序倒序

List userList3 = userList.stream() .sorted(Comparator.comparing(userInfo::getAge).thenComparing(userInfo::getMoney,Comparator.reverseOrder())) .collect(Collectors.toList());

5、LIst 转Map或Map转List  /List 中某个字段相同的,另一个字段求和

List result = totalList.stream().collect(Collectors.toMap(TotalBytesHostBean::getHost,

TotalBytesHostBean::getTotalBytes, (x, y) -> x + y))

.entrySet()

.stream()

.map(e -> new TotalBytesHostBean(e.getKey(),e.getValue()))

.sorted(Comparator.comparingLong(TotalBytesHostBean::getTotalBytes)).limit(10).collect(Collectors.toList());

可能有更好的写法、暂时没想到

持续更新中。。。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值