威海网站建设whhl,上海网站建设q479185700強,西安网站建设官网,网页设计架构Stream实战-统计
stream在开发中经常使用场景就是统计#xff0c;再次记录一下实际开发中用的到统计#xff0c;使用模拟数据。
需求如下#xff1a; 代码如下:
/*** map集合统计*/
public class StreamDemo4 {/*** 实体类*/DataAllArgsConstructorNoArgsConstructorclas…Stream实战-统计
stream在开发中经常使用场景就是统计再次记录一下实际开发中用的到统计使用模拟数据。
需求如下 代码如下:
/*** map集合统计*/
public class StreamDemo4 {/*** 实体类*/DataAllArgsConstructorNoArgsConstructorclass Book{/** 名称 */private String name;/** 数量 */private Integer count;}/*** 初始化集合*/public ListBook init(){return Stream.of(new Book(java,10),new Book(java,20),new Book(web,10),new Book(linux,10)).collect(Collectors.toList());}/*** map分组统计每科书的数量*/public MapString,Integer mapCount(){ListBook init init();return init.stream().collect(Collectors.groupingBy(Book::getName, Collectors.summingInt(Book::getCount)));}/*** Map 转换 List*/public ListBook mapConvertList(){MapString, Integer map mapCount();return map.entrySet().stream().map(entry - new Book(entry.getKey(), entry.getValue())).collect(Collectors.toList());}/*** list统计每科书的数量*/public ListBook listCount(){ListBook init init();return init.stream().collect(Collectors.groupingBy(Book::getName)).entrySet().stream().map(entry - {String name entry.getKey();int sum entry.getValue().stream().mapToInt(Book::getCount).sum();return new Book(name, sum);}).collect(Collectors.toList());}public ListBook groupAndSum() {ListBook init init();return init.stream().collect(Collectors.groupingBy(Book::getName,Collectors.reducing(0, Book::getCount, Integer::sum))).entrySet().stream().map(entry - new Book(entry.getKey(), entry.getValue())).collect(Collectors.toList());}public static void main(String[] args) {StreamDemo4 streamDemo4 new StreamDemo4();System.out.println( Map统计 );streamDemo4.mapCount().entrySet().forEach(System.out::println);System.out.println( Map转换List );streamDemo4.mapConvertList().forEach(System.out::println);System.out.println( List统计 );streamDemo4.listCount().forEach(System.out::println);System.out.println( List统计方式2 );streamDemo4.groupAndSum().forEach(System.out::println);}
}代码中的方法
groupingBy:对流进行分组,在此案例中把name当作Key把ListBook》当作valueentrySet把map集合转换成SetMapString,Integer》》格式map:提取原流中元素 进行处理mapToInt把结果转换成IntStream流sum和mapToInt搭配使用IntStream流的结果求和reducing:对流进行一些统计如求和求积统计最大最小等 进行处理mapToInt把结果转换成IntStream流sum和mapToInt搭配使用IntStream流的结果求和reducing:对流进行一些统计如求和求积统计最大最小等summingInt对整数流元素进行求和