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; /*** * *Create by 范春宇 on 2019/12/26 17:22 */ @Data public 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数组,先转化为List List<Integer> list= Arrays.stream(arr).boxed().collect(Collectors.toList()); //groupingBy分组 Map<Integer, Long> map = list.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); //控制台输出map map.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
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。