Lambda表达式遍历结合常用的一些操作

        Lambda 表达式是JDK 8的一个新特性,Lambad 可以取代大部分匿名内部类,写出更好的Java代码,尤其在集合的遍历和其它集合操作中,可以极大的优化代码结构。Lambda 由参数列表、箭头符号 -> 和函数体组成。

        stream()不是一种数据结构,它只是某种数据源的一个视图,数据源可以是一个数组,Java容器或I/O channel等。为函数式编程而生。对stream的任何修改都不会修改背后的数据源,比如对stream执行过滤操作并不会删除被过滤的元素,而是会产生一个不包含被过滤元素的新stream。stream上的操作并不会立即执行,只有等到用户真正需要结果的时候才会执行。stream只能被“消费”一次,一旦遍历过就会失效,就像容器的迭代器那样,想要再次遍历必须重新生成。

集合分组(获得Map<String, List<R>>)

分组写法

public static void main(String[] args) {
        // 构建实体对象 模拟从数据查到的数据 
        PersonEntity person1 = PersonEntity.builder().userId("1").userName("张三").userStatus("1").roomNumber("101").build();
        PersonEntity person_1 = PersonEntity.builder().userId("1").userName("张三").userStatus("-1").roomNumber("101").build();
        PersonEntity person2 = PersonEntity.builder().userId("2").userName("李四").userStatus("1").roomNumber("101").build();
        PersonEntity person3 = PersonEntity.builder().userId("3").userName("王五").userStatus("1").roomNumber("102").build();
        // personAllList添加实体 全部人员
        List<PersonEntity> personAllList = new ArrayList<>();
        personAllList.add(person1);
        personAllList.add(person2);
        personAllList.add(person3);
        Map<String, List<PersonEntity>> map = personAllList.stream().collect(Collectors.groupingBy(PersonEntity::getRoomNumber));
        System.out.println(map.toString());
    }

打印结果

{101=[PersonEntity(userId=1, userName=张三, userStatus=1, roomNumber=101), PersonEntity(userId=2, userName=李四, userStatus=1, roomNumber=101)], 102=[PersonEntity(userId=3, userName=王五, userStatus=1, roomNumber=102)]}

获取集合里实体属性最大值的某一个元素

 // 获取id最大的用户
Optional<PersonEntity> personEntity= personAllList.stream().max(Comparator.comparing(PersonEntity::getUserId));

获取集合里实体属性存为新MAP(Map<String, String>)

Map<String, String> map = list.stream().collect(Collectors.toMap(vo::getxxx, vo::getxxx));

Duplicate key  xxxx 的异常

我们在利用Lambda 将list转成Map时就会出现 Duplicate key  xxxx 的异常,意思就是对要转为map的key有重复了,除了进行for循环去重之外,我们还有其它方式能够优雅的处理它.

1.key重复时直接用后面的值(使用最新的或最老的值)
Map<String, Long> collect = enterpriseWechatRelations.stream().collect(Collectors.toMap(EnterpriseWechatRelation::getExternalUserId, EnterpriseWechatRelation::getUserId,(val1, val2) -> val2));
2.将两个值拼接起来
Map<String, Long> collect = enterpriseWechatRelations.stream().collect(Collectors.toMap(EnterpriseWechatRelation::getExternalUserId,EnterpriseWechatRelation::getUserId,(val1, val2) -> val1+val2));

获取结合里实体属性存在新的实体(List<BeanB>)

List<BeanB> newList = oldList.stream().map(e -> new BeanB(e.getId(), e.getName(), e.getAge())).collect(Collectors.toList());

表达式对age大小正序排序(sorted 和reversed())

// 正序
userInfoList = userInfoList.stream().sorted(Comparator.comparing(UserInfo::getAge)).collect(Collectors.toList());
// 逆序
userInfoList=userInfoList.stream().sorted(Comparator.comparing(UserInfo::getAge).reversed()) .collect(Collectors.toList());

根据某些属性过滤放入新的集合

List<Category> categoryList = categoryService.selectCategoryList(category);
// 选出所有一级分类放入新的集合
List<Category> listLevel1=categoryList.stream().filter((Category c) ->"1".equals(c.getCategoryLevel())).collect(Collectors.toList());

//    获取设备类型为102的摄像头集合
List<AiDevice> cameraList=list.stream().filter((AiDevice b)- 
>"102".equals(b.getDeviceType())).distinct().collect(Collectors.toList());
// 然后根据摄像头对应的gatemateId 找到需要下发的盒子信息
List<AiDevice> result = cameraList.stream().collect(Collectors.collectingAndThen(
Collectors.toCollection(() -> new TreeSet<> 
(Comparator.comparing(AiDevice::getGatewayId))), ArrayList::new));

根据名字去重

List<ProdAPP> list =listOld.stream().collect(
        Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.getProdName()))),ArrayList::new));

简单集合取交集、差集、并集、去重并集

List<String> list1 = new ArrayList();
List<String> list2 = new ArrayList();
// 交集
List<String> intersection = list1.stream().filter(item -> list2.contains(item)).collect(Collectors.toList());
// 差集 (list2 - list1)
List<String> reduce2 = list2.stream().filter(item -> !list1.contains(item)).collect(Collectors.toList());
// 并集
List<String> listAll = list1.parallelStream().collect(Collectors.toList());
List<String> listAll2 = list2.parallelStream().collect(Collectors.toList());
listAll.addAll(listAll2);
// 去重并集
List<String> listAllDistinct = listAll.stream().distinct().collect(Collectors.toList());

一些求和、累计用到lambda

 // 汇总1:单列累加 
goodsInfoList.stream().map(GoodsInfoDTO::getPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
// 汇总2:先过滤再单列累加(55.0)
goodsInfoList.stream().filter(goods ->         
"MATERIAL".equals(goods.getGoodsType())).map(GoodsInfoDTO::getPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
// 汇总3:双列乘积并累加
goodsInfoList.stream().map(x -> x.getPrice().multiply(BigDecimal.valueOf(x.getQty()))).reduce(BigDecimal.ZERO, BigDecimal::add);
// 积汇4:双列乘积并累加
goodsInfoList.stream().reduce(BigDecimal.ZERO, (x, y) -> {
            return x.add(y.getPrice().multiply(BigDecimal.valueOf(y.getQty())));
        }, BigDecimal::add);
// 整形
 list.stream().mapToInt(a->a.getCount()).sum()
// double类型
list.stream().mapToDouble(a->a.getWeight()).sum();
// Long类型
list.stream().mapToLong(a -> a.getPri()).sum();
// BigDecimal类型
list.stream().map(Animal::getMoney).reduce(BigDecimal.ZERO, BigDecimal::add);

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一棵小白菜#

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值