本篇内容介绍了“java8怎么实现分组计算数量和计算总数”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!
java8分组计算数量和计算总数
package com.pig4cloud.pigx.admin.api.vo;import lombok.Builder;import lombok.Data;import lombok.experimental.Tolerate;import java.util.*;import java.util.stream.Collectors;@Datapublic class RealSkuVo implements Cloneable{private String realEan;private Integer realQty;public static void main(String[] args) throws CloneNotSupportedException {List<RealSkuVo> list = new ArrayList<>();RealSkuVo a = new RealSkuVo();RealSkuVo b1 = (RealSkuVo)a.clone();b1.setRealEan("asdasda");b1.setRealQty(1);RealSkuVo b2 = (RealSkuVo)a.clone();b2.setRealEan("asdasda2");b2.setRealQty(1);RealSkuVo b3 = (RealSkuVo)a.clone();b3.setRealEan("asdasda3");b3.setRealQty(1);RealSkuVo b4 = (RealSkuVo)a.clone();b4.setRealEan("asdasda3");b4.setRealQty(1);list.add(b1);list.add(b2);list.add(b3);list.add(b4);Map<String, LongSummaryStatistics> collect = list.stream().collect(Collectors.groupingBy(RealSkuVo::getRealEan,Collectors.summarizingLong(RealSkuVo::getRealQty)));Map<String, Long> collect1 = list.stream().collect(Collectors.groupingBy(RealSkuVo::getRealEan, Collectors.counting()));System.out.println(collect);}}
Java8利用Stream分组统计List(或数组)中元素的个数,结果存放在Map
int[] arr=new int[]{5,1,3,4,1};//若统计的是int数组,先转化为ListList<Integer> list= Arrays.stream(arr).boxed().collect(Collectors.toList());//groupingBy分组Map<Integer, Long> map = list.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));//控制台输出mapmap.forEach((k,v)->{ System.out.println("k="+k+",v="+v);});
k=1,v=2
k=3,v=1
k=4,v=1
k=5,v=1
“java8怎么实现分组计算数量和计算总数”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注编程网网站,小编将为大家输出更多高质量的实用文章!