Java8 stream对List<Map<String,Object>>常用的数据处理

java 8 在推出stream 之后 对于集合等数据的处理用了就回不去了,在此处做个笔记。

查数据
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()))); 

**3.根据map中的某个keyvalue值进行判断过滤**

List<Map<String,Object>> 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<Map<String, Object>> res = prnInfo .stream().
                filter(
                        map -> LocalDateTime.parse(map.get("starttm")+"", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")).isBefore(tm )
                ).collect(Collectors.toList());
                
------------------------------------------------------------------------

                          

**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());


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();

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);
            }
        }

你可能感兴趣的:(java)