Java8 Stream分组统计、扁平化操作

1、初始化统计数据

@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@ToString
public class SiteBean {

    private Integer  id;

    ///  场地编号
    private String   siteNo;

    /// 已经使用桌子数量
    private Integer  useNum;

   /// 需要维修数量
    private Integer  unBingNum;

    /// 桌子总数量
    private Integer   total;

}
    public  static List  initSiteList(){
        List list  =new ArrayList<>();
        list.add(new SiteBean(1,"s001",10,3,15));
        list.add(new SiteBean(2,"s002",15,4,20));
        list.add(new SiteBean(3,"s003",15,6,20));
        list.add(new SiteBean(4,"s001",20,3,20));
        list.add(new SiteBean(5,"s002",16,10,25));
        return list;
    }

2、分组统计

   现需统计各个场地的总数、使用数、需要维修数

 // 按照场地进行分组  
Map>  groupMap = list.stream().collect(Collectors.groupingBy(SiteBean::getSiteNo, Collectors.toList()));
      
 //   统计每个场地的数据
List listRes = groupMap.keySet().stream().map(key -> {
            List set = groupMap.get(key);
            SiteBean siteBean = new SiteBean();
            siteBean.setSiteNo(key);
            siteBean.setTotal(set.stream().mapToInt(SiteBean::getTotal).sum());
            siteBean.setUseNum(set.stream().mapToInt(SiteBean::getUseNum).sum());
            siteBean.setUnBingNum(set.stream().mapToInt(SiteBean::getUnBingNum).sum());
            return siteBean;
        }).collect(Collectors.toList());
        System.out.println("listRes-----"+listRes);

3、flatMap扁平化操作

   将"Apache Storm","Spark Streaming","Apache Flink"三组词按照空格切分,存入list

   String[]  sourceStr = {"Apache Storm","Spark Streaming","Apache Flink"};
   List flatMapList = Arrays.stream(sourceStr).map(s -> s.split(" ")).flatMap(Arrays::stream).collect(Collectors.toList());
        System.out.println("flatMapList----"+flatMapList);

你可能感兴趣的:(JavaWeb,java)