Java8中通过Stream 对列表分组的groupBy 的使⽤
对List 进⾏分组(java8的Stream 分组的groupBy 的使⽤)
最近在做⼀个功能:对⼀个接⼝接收的List数据进⾏校验,同⼀个订单⾥的⼀个产品id只能添加⼀次。本来想是在⼊库的时候通过SQL语句进⾏处理的。但是由于这个数据接⼝之前同事写了很多的校验,是在是⼜*⼜长。在度娘上查⼀下,发现了JAVA8 可以通过Stream对List 进⾏处理(这⾥主要是关于分组的);
如果需要分组前进⾏判断,可以加个过滤;
需要通过两个字段进⾏分组,groupingBy ⾥⾯加了两个字段;
分组是按照groupingBy⾥⾯拼接的字段进⾏分组的,我这⾥加上";"主要是为了区分订单号和产品号;
上⾯是groupingBy分组器最多见的⼀个⽤法,下⾯简单介绍⼀下其余⽤法:
统计每⼀个分组的count
统计分组平均值
统计分组总值Order order1 = new  Order ();order1.setOrderId ("123");Order1.setGoodsId ("S1");Order1.setSales (100);Order order2 = new  Order ();order2.setOrderId ("123");Order2.setGoodsId ("S2");Order1.setSales (200);Order order2 = new  Order ();order2.setOrderId ("1234");Order2.setGoodsId ("S3");Order1.setSales (300);List <Order > list =  new  ArrayList ();List .add (order1);List .add (order2);List .add (order3);Map <String ,List <Order >> map = list .stream ().collect (Collectors .groupingBy (ord -> ord .getOrderId ));//或 Map<String,List<Order>> map = list.stream().upingBy(Order::getOrderId));
1
2
3groupby分组
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22Map <String ,List <Order >> map = list .stream ().filter (ord -> ord .getOrderId != null ).collect (Collectors .groupingBy (h -> h .getOrderID ));
1
2Map <String ,List <Order >> map = list .stream ().collect (Collectors .groupingBy (ord -> ord .getOrderId +“;”+ ord .getOrderGoodsId ()));
1/** * 使⽤java8 stream groupingBy 操做,按城市分组list 统计count  */Map <String ,Long > map = list .stream ().collect (Collectors .groupingBy (Order ::getOrderId ,  Collectors .counting ()));
1
2
3
4/** * 使⽤java8 stream groupingBy 操做,按城市分组list 并计算分组销售平均值 */ Map <String ,Long > map = list .stream ().collect (Collectors .groupingBy (Order ::getOrderId ,  Collectors .averagingInt (Order ::getSales )));1
2
3
4
相关链接/** * 使⽤java8 stream groupingBy 操做,按城市分组list 并计算分组销售总值 */ Map <String ,Long > map = list .stream ().collect (Collectors .groupingBy (Order ::getOrderId ,  Collectors .summingLong (Order ::getSales ))); //对Map 按照分组销售总值逆序排序 Map <String , Long > finalMap = new  LinkedHashMap <>(); map .entrySet ().stream ()        .sorted (Map .Entry .<String , Long >comparingByValue ()                .reversed ()).forEachOrdered (e -> finalMap .put (e .getKey (), e .getValue ()));12345678910

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。