• lamba stream处理集合


    lamdba stream处理集合

    HashMap对象的key、value值均可为null。
    HahTable对象的key、value值均不可为null。
    注意:stream方式转换封装map的value不能为null
    封装Table

    Table<String, String, Long> table = HashBasedTable.create();
    dimensionDetailData.forEach(n->table.put(n.getName(),n.getDimensionValue(),n.getId()));
    
    • 1
    • 2

    多层map封装Map>

    Map<String, Map<String, Long>> dimensionDetailData.stream().collect(Collectors.groupingBy(ETLDimensionDTO::getColumnName,
                    Collectors.toMap(ETLDimensionDTO::getDimensionValue, ETLDimensionDTO::getId)));
    
    • 1
    • 2

    不想创建新封装类,使用元祖封装map的value

    Map<Long, Pair<String, Long>> map = new HashMap<>();
    for (DimensionValue obj : list) {
        map.put(obj.getId(), Pair.of(obj.getDimensionValue(), obj.getDimensionId()));
    }
    
    • 1
    • 2
    • 3
    • 4

    指定key-value,value是对象本身,User->User 是一个返回本身的lambda表达式

    Map<Integer,User> userMap2 = userList.stream().collect(Collectors.toMap(User::getId,User->User));
    
    • 1

    指定key-value,value是对象本身,Function.identity()是简洁写法,也是返回对象本身

    Map<Integer,User> userMap3 = userList.stream().collect(Collectors.toMap(User::getId, Function.identity()));
    
    • 1

    指定key-value,value是对象本身,Function.identity()是简洁写法,也是返回对象本身,key 冲突的解决办法,这里选择第二个key覆盖第一个key。

    Map<Integer,User> userMap4 = userList.stream().collect(Collectors.toMap(User::getId, Function.identity(),(key1,key2)->key2));
    
    • 1

    之前将Long数据,检查数据就不用转,不会出现数据转换异常

    Map<String,String> dimensionMap= dimensionValues.stream().filter(m->m.getDimensionValue()!=null && null!=m.getId())
    .collect(Collectors.toMap(m->m.getId().toString(), DimensionValue::getDimensionValue));
    
    • 1
    • 2

    List>> 按key分组

    Map<String, List<Map<String, Object>>> groupList = mapList.stream()
                    .collect(Collectors.groupingBy(map -> map.get(ColumnConstants.GROUP_ID).toString()));
    
    • 1
    • 2

    stream流把list中的某个属性转为set

    Set<String> set= list.stream().map(实体::get属性).collect(Collectors.toSet));
    
    • 1

    带拼接多字段分组List< Object> 转 Map>

    Map<String, List<ProfitAndLossMapping>> collect = plMappingList.stream()
    .collect(Collectors.groupingBy(m -> m.getLosType() + ":" + m.getRuleType()));
    
    • 1
    • 2

    带拼接多字段分组List< Object> 转 Map

    List<LosNameListByFy> losNameListByFIES = losNameListByFyMapper.selectList(null);
    Map<String, String> losMap = losNameListByFIES.stream()
    .collect(Collectors.toMap(o -> o.getFy() + ":" + o.getLos(), LosNameListByFy::getNewLos));
    
    • 1
    • 2
    • 3

    List< Object> 转 Map

    Map<String, Long> reportOrgIdMap = reportOrgConfs.stream()
    .collect(Collectors.groupingBy(m -> m.getReport() + ":" + m.getOrgId(), Collectors.counting()));
    
    • 1
    • 2

    List< Object> 转 Map

     Map<String, BigDecimal> avgMap = summaryInitList.stream()
     .collect(HashMap::new, (map, item) -> map.put(item.getCombinedValue(), item.getValue()), HashMap::putAll);
    Map<String,String> columnAndDimensionMap=dimensions.stream()
    .filter(m->StringUtils.isNotBlank(m.getColumnName()))
    .collect(Collectors.toMap(Dimension::getColumnName, Dimension::getName, (key1, key2) -> key1));
    
    • 1
    • 2
    • 3
    • 4
    • 5

    List< String> 转 Map

    Map<String,String> reportMap=report.stream()
    .filter(StringUtils::isNotBlank)
    .collect(Collectors.toMap(Function.identity(),Function.identity()));
    
    • 1
    • 2
    • 3

    List< Object> 转 Map>

    Map<String, List<DictItemDetailVO>> map = list.stream()
    .collect(Collectors.groupingBy(DictItemDetailVO::getDescription));
    
    • 1
    • 2

    List< String>去重 拼接

    List<String> list = Arrays.asList("AA", "BB", "CC", "BB", "CC", "AA", "AA");
    long l = list.stream().distinct().count();
    System.out.println("No. of distinct elements:"+l);
    String output = list.stream().distinct().collect(Collectors.joining(","));
    System.out.println(output);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    List<Map<String, String>> list = new ArrayList<>();
    {
        Map<String, String> map = new HashMap<>();
        map.put("id", "1");
        map.put("name", "B");
        map.put("age", "C");
        list.add(map);
    }
    {
        Map<String, String> map = new HashMap<>();
        map.put("id", "1");
        map.put("name", "E");
        map.put("age", "F");
        list.add(map);
    }
     
    //1.返回结果{"1","B"},{"2","E"}
    Map<String, String> a = list.stream().collect(Collectors.toMap(l -> l.get("id"), 
    l -> l.get("name")));
    //2.两种方法返回结果{"1":{"name":"B","id":"1","age":"C"},"2":{"name":"E","id":"2","age":"F"}}
    Map<String, Map> b = list.stream().collect(Collectors.toMap(l -> l.get("id"), map -> map));
    Map<String, Map> c = list.stream().collect(Collectors.toMap(l -> l.get("id"), 
    Function.identity()));
    //3.重复key情况下处理方式返回结果{"1":{"name":"E","id":"1","age":"F"}}
    Map<String, Map> d = list.stream().collect(Collectors.toMap(l -> l.get("id"), 
    Function.identity(), (key1, key2) -> key2));
    //4.重复key情况下指定返回数据类型处理方式返回结果{"1":{"name":"E","id":"1","age":"F"}}
    Map<String, Map> e = list.stream().collect(Collectors.toMap(l -> l.get("id"), 
    Function.identity(), (key1, key2) -> key2, LinkedHashMap::new));
     
     
    //5.list根据key合并并转map;返回结果{"1":[{"name":"B","id":"1","age":"C"},{"name":"E","id":"1","age":"F"}]}
    Map<String, List<Map>> lableGbType = list.stream()
    .collect(Collectors.groupingBy(l -> (String) l.get("id")));
            
    //6.根据key提取list中指定的值转List数组;返回结果["1","1"]
    List<String> ids = list.stream().map(m -> (String) m.get("id"))
    .collect(Collectors.toList());
     
     
    //7.数组去重并转list
    String[] str = "1,1,2,3,4,5,".split(",");
    List<String> listNames = Arrays.stream(str).filter(name -> !isEmpty(name)).distinct().collect(Collectors.toList());
     
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    查数据
    List<Map<String, Object>> prnInfo = xxxMapper.selectInfo(pars);
    
    List<String> ids= prnInfo.stream().map(m -> m.get("id").toString()).collect(Collectors.toList());
    
    **1.根据map的某个key分组**
    Map<String, List<Map<String, Object>>> res= dataList.stream().collect(
                    groupingBy(map -> map.get("d").toString()));
    获取type="ZC"的数据        
    ----------------------------------------------------------------     
    List<Map<String, Object>> data = res.stream().
                    filter(
                            map -> (map.get("type")+"").equals("ZC")
                    ).collect(Collectors.toList());
    -----------------------------------------------------------------
    List<Map<String, Object>> res = prnInfo .stream().filter(e ->Integer.parseInt(e.get("caseFlag").toString()) != 0)
    .collect(Collectors.toList());
    
    **2.根据某个key求对应value和**
    int totalNums= prnInfo .stream().collect(Collectors.summingInt( e -> Integer.parseInt(e.get("num").toString()))); 
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    
    **3.根据map中的某个key的value值进行判断过滤**
    
    List> res= prnInfo .stream().filter(e -> Double.parseDouble(e.get("z").toString())>Double.parseDouble(e.get("wrz").toString()))
                    .collect(Collectors.toList());
    ------------------------------------------------------------------------
    获取指XX时间前后的数据
    LocalDateTime ftm = "xxxxxxxxx";
    List> res = prnInfo .stream().
                    filter(
                            map -> LocalDateTime.parse(map.get("starttm")+"", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")).isBefore(tm )
                    ).collect(Collectors.toList());
                    
    ------------------------------------------------------------------------
                           
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    **4.对集合中的map做变更**
    List<Map<String, Object>> res= prnInfo .stream().map(x -> {
                    x.put("encd", Double.parseDouble(x.get("rz")+"")-Double.parseDouble(x.get("tdz")+""));
                return x;
            }).collect(Collectors.toList());
    
    
    **5.排序**
    List<Map<String, Object>>  res= prnInfo.stream().sorted((e1,e2) -> {
    return -Double.compare(Double.valueOf(e1.get("num").toString()),Double.valueOf(e2.get("num").toString()));
    }).collect(Collectors.toList());
    
    
    res.sort(Comparator.comparing((Map<String, Object> h) -> (h.get("tm").toString())));
    
    //排序可能对应字段数据为null导致空指针,需要先判断过滤一下
    res.stream().filter(Objects::nonNull).filter((Map<String, Object> h)
                        -> (Objects.nonNull(h.get("fz")))).collect(Collectors.toList());
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    
    6.去重
    List<String> res = prnInfo.stream().distinct().collect(Collectors.toList());
    
    
    7.做统计
    IntSummaryStatistics collect = list.stream().collect(Collectors.summarizingInt(Test::getId));
    System.out.println("和:" + collect.getSum());
    System.out.println("数量:" + collect.getCount());
    System.out.println("最大值:" + collect.getMax());
    System.out.println("最小值:" + collect.getMin());
    System.out.println("平均值:" + collect.getAverage());
    
    最大
    double max = prnInfo.stream().mapToDouble(l -> ((BigDecimal) l.get("num")).doubleValue()).max().getAsDouble();double sum = prnInfo.stream().mapToDouble(l -> ((BigDecimal) l.get("num")).doubleValue()).sum();
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    8.list-map转换
    Map<String, Object> map = list.stream()
    				.collect(Collectors.toMap(i -> i.getName() + i.getUnitName(), j -> j, (k1, k2) -> k1));
    				
    ------------------------------------------------------------------------
    List<User> collect = map.entrySet().stream().map(item -> {
    			User user= new User();
    			user.setId(item.getKey());
    			user.setName(item.getValue());
    			return user;
    		}).collect(Collectors.toList());
    
    遍历。。
    users.stream().forEach(x->{
        System.out.println(x);
    });
    
    下面这个场景用的也很多,List里面的a和b相等就把c属性相加,报表里面某些属性相等则求和等场景,可以先根据需要去重的多个字段进行分组,再计算返回
    for (Map.Entry<String, List<DTO>> entry : beanList.parallelStream().collect(groupingBy(o -> (o.getId() + o.geCode()), Collectors.toList())).entrySet()) {
          if(bitMap.contains(entry.getKey()) && entry.getValue().size()==1){
               objects.add(entry.getValue().get(0));
          }else{
               List<DTO> transfer = entry.getValue();
               transfer.stream().reduce((a, b) -> DTO.builder()
                    .irrCd(a.getIrrCd())
                    .id(a.getId())
                    .tm(a.getCode())
                    .build())
                    .ifPresent(objects::add);
                }
            }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32

    List 排序

    1, 对象集合排序
    //降序,根据创建时间降序;

    List<User> descList = attributeList.stream()
    .sorted(Comparator.comparing(User::getCreateTime,Comparator.nullsLast(Date::compareTo)).reversed())
    .collect(Collectors.toList());
    
    • 1
    • 2
    • 3

    //升序,根据创建时间升序;

    List<User> ascList = attributeList.stream()
    .sorted(Comparator.comparing(User::getCreateTime,Comparator.nullsLast(Date::compareTo))).collect(Collectors.toList());
    
    • 1
    • 2

    2, 数字排序

    List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
    
    • 1

    //升序

     List<Integer> ascList = numbers.stream().sorted().collect(Collectors.toList());
    
    • 1

    结果: [2, 2, 3, 3, 3, 5, 7]

    //倒序

     List<Integer> descList = numbers.stream().sorted((x, y) -> y - x).collect(Collectors.toList());
    
    • 1

    结果:[7, 5, 3, 3, 3, 2, 2]

    3, 字符串排序

    List<String> strList = Arrays.asList("a", "ba", "bb", "abc", "cbb", "bba", "cab");
    
    • 1

    //自然排序

    List<String> ascList = strList.stream().sorted().collect(Collectors.toList());
    
    • 1

    结果:[a, abc, ba, bb, bba, cab, cbb]

    //反转,倒序

    ascList.sort(Collections.reverseOrder());
    
    • 1

    结果:[cbb, cab, bba, bb, ba, abc, a]

    //直接反转集合

    Collections.reverse(strList);
    
    • 1

    结果:[cab, bba, cbb, abc, bb, ba, a]

    Map排序

    //HashMap是无序的,当我们希望有顺序地去存储key-value时,就需要使用LinkedHashMap了,排序后可以再转成HashMap。
    //LinkedHashMap是继承于HashMap,是基于HashMap和双向链表来实现的。
    //LinkedHashMap是线程不安全的。

    Map<String,String> map = new HashMap<>();
    map.put("a","123");
    map.put("b","456");
    map.put("z","789");
    map.put("c","234");
    
    • 1
    • 2
    • 3
    • 4
    • 5

    //map根据value正序排序

    LinkedHashMap<String, String> linkedMap1 = new LinkedHashMap<>();
    map.entrySet().stream().sorted(Comparator.comparing(e -> e.getValue()))
    .forEach(x -> linkedMap1.put(x.getKey(), x.getValue()));
    
    • 1
    • 2
    • 3

    结果:{a=123, c=234, b=456, z=789}
    //map根据value倒序排序

    LinkedHashMap<String, String> linkedMap2 = new LinkedHashMap<>();
    map.entrySet().stream().sorted(Collections.reverseOrder(Map.Entry.comparingByValue()))
    .forEach(x -> linkedMap2.put(x.getKey(), x.getValue()));
    
    • 1
    • 2
    • 3

    结果:{z=789, b=456, c=234, a=123}
    //map根据key正序排序

    LinkedHashMap<String, String> linkedMap3 = new LinkedHashMap<>();
    map.entrySet().stream().sorted(Comparator.comparing(e -> e.getKey()))
    .forEach(x -> linkedMap3.put(x.getKey(), x.getValue()));
    
    • 1
    • 2
    • 3

    结果:{a=123, b=456, c=234, z=789}
    //map根据key倒序排序

    LinkedHashMap<String, String> linkedMap4 = new LinkedHashMap<>();
    map.entrySet().stream().sorted(Collections.reverseOrder(Map.Entry.comparingByKey()))
    .forEach(x -> linkedMap4.put(x.getKey(), x.getValue()));
    
    • 1
    • 2
    • 3

    结果:{z=789, c=234, b=456, a=123}

    List 转 Map

    1、指定key-value,value是对象中的某个属性值。

    Map<Integer,String> userMap1 = userList.stream().collect(Collectors.toMap(User::getId,User::getName));
    
    • 1

    2、指定key-value,value是对象本身,User->User 是一个返回本身的lambda表达式

    Map<Integer,User> userMap2 = userList.stream().collect(Collectors.toMap(User::getId,User->User));
    
    • 1

    3、指定key-value,value是对象本身,Function.identity()是简洁写法,也是返回对象本身

    Map<Integer,User> userMap3 = userList.stream().collect(Collectors.toMap(User::getId, Function.identity()));
    
    • 1

    4、指定key-value,value是对象本身,Function.identity()是简洁写法,也是返回对象本身,key 冲突的解决办法,这里选择第二个key覆盖第一个key。

    Map<Integer,User> userMap4 = userList.stream().collect(Collectors.toMap(User::getId, Function.identity(),(key1,key2)->key2));
    
    • 1
    5、将List根据某个属性进行分组,放入Map;然后组装成key-value格式的数据,分组后集合的顺序会被改变,所以事先设置下排序,然后再排序,保证数据顺序不变。
    
    • 1
    List<GoodsInfoOut> lst = goodsInfoMapper.getGoodsList();
     Map<String, List<GoodsInfoOut>> groupMap = lst.stream().collect(Collectors.groupingBy(GoodsInfoOut::getClassificationOperationId));
       List<HomeGoodsInfoOut> retList = groupMap.keySet().stream().map(key -> {
           HomeGoodsInfoOut mallOut = new HomeGoodsInfoOut();
           mallOut.setClassificationOperationId(key);
           if(groupMap.get(key)!=null && groupMap.get(key).size()>0) {
               mallOut.setClassificationName(groupMap.get(key).get(0).getClassificationName());
               mallOut.setClassificationPic(groupMap.get(key).get(0).getClassificationPic());
               mallOut.setClassificationSort(groupMap.get(key).get(0).getClassificationSort());
           }
           mallOut.setGoodsInfoList(groupMap.get(key));
           return mallOut;
       }).collect(Collectors.toList());
       List<HomeGoodsInfoOut> homeGoodsInfoOutList = retList.stream().sorted(Comparator.comparing(HomeGoodsInfoOut::getClassificationSort))                                .collect(Collectors.toList());
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    5、根据用户性别将数据 - 分组

     Map<String, List<UserInfo>> groupMap = userList.stream().collect(Collectors.groupingBy(UserInfo::getSex()));
    
    • 1

    6、List实体转Map,想要有序的话,就使用以下操作(TreeMap 有序;Map 无序)

    TreeMap<String, List<BillPollEntity>> ascMonthBillPollMap = s.stream()
    .collect(Collectors.groupingBy(t -> t.getDrawTime()), TreeMap::new, Collectors.toList()));
    
    • 1
    • 2

    //倒序MAP

    NavigableMap<String, List<OpenActivityOut>> descMonthBillPollMap = ascMonthBillPollMap.descendingMap();
    Map<String, List<BillPollEntity>> monthBillPollMap = s.stream().collect(Collectors.groupingBy(BillPollEntity::getDrawTime));
    
    • 1
    • 2

    三,Map 转 List

    Map map1 = new HashMap<>();
    map1.put(“a”,“123”);
    map1.put(“b”,“456”);
    map1.put(“z”,“789”);
    map1.put(“c”,“234”);

        1、默认顺序
        List list0 = map1.entrySet().stream()
    
    • 1
    • 2

    .map(e -> new UserInfo(e.getValue(), e.getKey()))
                       .collect(Collectors.toList());
    结果:[UserInfo(userName=123, mobile=a), UserInfo(userName=456, mobile=b), UserInfo(userName=234, mobile=c), UserInfo(userName=789, mobile=z)]

        2、根据Key排序
        List list1 = map1.entrySet().stream()
    
    • 1
    • 2

    .sorted(Comparator.comparing(e -> e.getKey())).map(e -> new UserInfo(e.getKey(), e.getValue()))
                       .collect(Collectors.toList());
    结果:[UserInfo(userName=a, mobile=123), UserInfo(userName=b, mobile=456), UserInfo(userName=c, mobile=234), UserInfo(userName=z, mobile=789)]

        3、根据Value排序
        List list2 = map1.entrySet().stream()
    
    • 1
    • 2

    .sorted(Comparator.comparing(Map.Entry::getValue))
                      .map(e -> new UserInfo(e.getKey(), e.getValue()))
                      .collect(Collectors.toList());
    结果:[UserInfo(userName=a, mobile=123), UserInfo(userName=c, mobile=234), UserInfo(userName=b, mobile=456), UserInfo(userName=z, mobile=789)]

        3、根据Key排序
        List list3 = map1.entrySet().stream()
    
    • 1
    • 2

    .sorted(Map.Entry.comparingByKey())
                      .map(e -> new UserInfo(e.getKey(), e.getValue()))
                      .collect(Collectors.toList());
    结果:[UserInfo(userName=a, mobile=123), UserInfo(userName=b, mobile=456), UserInfo(userName=c, mobile=234), UserInfo(userName=z, mobile=789)]

    4、Map 转 List、List
          // 取Map中的所有value
          结果:List userInfoList = retMap.values().stream().collect(Collectors.toList());
          // 取Map中所有key
          结果:List strList = retMap.keySet().stream().collect(Collectors.toList());

    四,从List中获取某个属性

    //拿出所有手机号
    List mobileList = userList.stream().map(RemindUserOut::getMobile).collect(Collectors.toList());
    //拿出所有AppId,并去重
    List appIdList = appIdList.stream().map(WechatWebViewDomain::getAppId).collect(Collectors.toList()).stream().distinct().collect(Collectors.toList());
    //拿出集合中重复的billNo,【.filter(map->StringUtils.isNotEmpty(map.getBillNo()))】这是过滤掉为空的数据;否则,有空数据会抛异常
    List repeatCodeList = resultList.stream().filter(map->StringUtils.isNotEmpty(map.getBillNo())).collect(Collectors.groupingBy(BillUploadIn::getBillNo, Collectors.counting())).entrySet().stream().filter(entry -> entry.getValue() > 1).map(Map.Entry::getKey).collect(Collectors.toList());

    //拿出集合中几个属性拼接后的字符串
    List strList = myList.stream().map(p -> p.getName() + “-” + p.getMobile()).collect(Collectors.toList());
    五,筛选并根据属性去重

    List uList = new ArrayList<>();
    UserInfo u1 = new UserInfo(1,“小白”,“15600000000”);
    UserInfo u2 = new UserInfo(2,“小黑”,“15500000000”);
    uList.add(u1);
    uList.add(u2);

    //过滤名字是小白的数据
    List list1= uList.stream()
    .filter(b -> “小白”.equals(b.getUserName()))
    .collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(b -> b.getId()))), ArrayList::new));
    结果:list1===[UserInfo(id=1, userName=小白, mobile=15600000000)]

    //根据ID去重
    List list2= uList.stream()
    .collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(b -> b.getId()))), ArrayList::new));
    结果:list2===[UserInfo(id=1, userName=小白, mobile=15600000000), UserInfo(id=2, userName=小黑, mobile=15500000000)]

    //整个数据去重
    list = list.stream().distinct().collect(Collectors.toList());

    六,计算;和,最大,最小,平均值。

    List uList = new ArrayList<>();
    UserInfo user1 = new UserInfo(1,“小白”,“15600000000”,10,new BigDecimal(10));
    UserInfo user2 = new UserInfo(2,“小黑”,“15500000000”,15,new BigDecimal(20));
    UserInfo user3 = new UserInfo(2,“小彩”,“15500000000”,88,new BigDecimal(99));
    uList.add(user1);
    uList.add(user2);
    uList.add(user3);

    //和
    Double d1 = uList.stream().mapToDouble(UserInfo::getNum).sum();
    结果:113.0
    //最大
    Double d2 = uList.stream().mapToDouble(UserInfo::getNum).max().getAsDouble();
    结果:88.0
    //最小
    Double d3 = uList.stream().mapToDouble(UserInfo::getNum).min().getAsDouble();
    结果:10.0
    //平均值
    Double d4 = uList.stream().mapToDouble(UserInfo::getNum).average().getAsDouble();
    结果:37.666666666666664

    //除了统计double类型,还有int和long,bigDecimal需要用到reduce求和
    DecimalFormat df = new DecimalFormat(“0.00”);//保留两位小数点
    //和;可过滤掉NULL值
    BigDecimal add = uList.stream().map(UserInfo::getPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
    BigDecimal add = uList.stream().filter(s->t.getPrice()!=null).map(UserInfo::getPrice).reduce(BigDecimal.ZERO, BigDecimal::add)
    System.out.println(df.format(add));
    结果:129.00
    //最大
    Optional max = uList.stream().max((u1, u2) -> u1.getNum().compareTo(u2.getNum()));
    System.out.println(df.format(max.get().getPrice()));
    结果:99.00
    //最小
    Optional min = uList.stream().min((u1, u2) -> u1.getNum().compareTo(u2.getNum()));
    System.out.println(df.format(min.get().getPrice()));
    结果:10.00

    //求和,还有mapToInt、mapToLong、flatMapToDouble、flatMapToInt、flatMapToLong
    list.stream().mapToDouble(UserInfo::getNum).sum();
    //最大
    list.stream().mapToDouble(UserInfo::getNum).max();
    //最小
    list.stream().mapToDouble(UserInfo::getNum).min();
    //平均值
    list.stream().mapToDouble(UserInfo::getNum).average();

    //获取N个List中,最大数组长度
    List valueList = new ArrayList<>();
    List tagList = valueList.stream().filter(v -> v.getTagList() != null && v.getTagList().size() > 0).map(OrderExcelOut::getTagList).collect(Collectors.toList());
    Optional maxTagList = tagList.stream().max((u1, u2) -> Integer.valueOf(u1.size()).compareTo(u2.size()));
    //数组中最长的数组
    maxTagList.get().size();

    原文链接:https://blog.csdn.net/y19910825/article/details/128107210

  • 相关阅读:
    Vuex详解
    《Python编程:从入门到实践》第二章练习题
    Github学生认证
    视频云存储平台LntonCVS国标视频平台功能和应用场景详细介绍
    第十一周周报
    如何配置jupyter远程交互环境?
    物联网与元宇宙融合发展
    Jellyfish and Green Apple-Codeforces Round 902 (Div. 2)
    Debian install MySQL if use root remove command ‘sudo‘
    SpringBoot集成Microsoft office 365账号方案(InsCode AI 创作助手)
  • 原文地址:https://blog.csdn.net/qq_33271461/article/details/134195855