根据单/多字段分组
单字段分组可以直接使用指定字段,多字段分组则采用拼接Key的形式
单字段:
//单字段分组Map> singleAttr = list.stream().collect( Collectors.groupingBy(t -> t.getNativePlace()));//还可以写成简化版//Map> collect = list.stream().collect(// Collectors.groupingBy(User::getNativePlace));
多字段:
//多字段分组Map> multiAttr = list.stream().collect( Collectors.groupingBy(t -> t.getNativePlace()+"_"+t.getAge()));
多层级:
//多级分组Map>> multiLevel = list.stream().collect( Collectors.groupingBy( t -> t.getNativePlace(), Collectors.groupingBy(t -> t.getAge()) ));
测试
package test;import java.util.ArrayList;import java.util.List;import java.util.Map;import java.util.Optional;import java.util.stream.Collectors;public class Test { public static void main(String[] args) { ArrayList list=new ArrayList(); list.add(new User(11,"a")); list.add(new User(12,"a")); list.add(new User(14,"c")); list.add(new User(14,"c")); //单字段分组 Map> singleAttr = list.stream().collect(Collectors.groupingBy(t -> t.getNativePlace())); //还可以写成简化版 //Map> collect = list.stream().collect(Collectors.groupingBy(User::getNativePlace)); //多字段分组 Map> multiAttr = list.stream().collect(Collectors.groupingBy(t -> t.getNativePlace()+"_"+t.getAge())); //多级分组 Map>> multiLevel = list.stream().collect( Collectors.groupingBy( t -> t.getNativePlace(), Collectors.groupingBy(t -> t.getAge()) ) ); }}class User{ private int age; private String nativePlace; public String getNativePlace() { return nativePlace; } public void setNativePlace(String nativePlace) { this.nativePlace = nativePlace; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public User(int age,String nativePlace) { this.age = age; this.nativePlace=nativePlace; }}
来源地址:https://blog.csdn.net/zcy_wxy/article/details/130192370