How does java8 realize the number of grouping calculations and the total number of calculations

  • 2021-10-16 01:54:43
  • OfStack

java8 Number of Group Calculations and Total Calculations


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  Fan Chunyu  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 uses Stream grouping to count the number of elements in List (or array), and the results are stored in Map


int[] arr=new int[]{5,1,3,4,1};
// If the statistics are int Array, first converted to List
List<Integer> list= Arrays.stream(arr).boxed().collect(Collectors.toList());
//groupingBy Grouping 
Map<Integer, Long> map = list.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
// Console output 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


Related articles: