1、Collections.groupingBy() 单字段分组
@ToString
@Data
@AllArgsConstructor
public class People {
private Integer id;
private String name;
private String address;
private Integer age;
}
测试类
public static void main(String[] args) {
People people1 = new People(1, "only-qi1", "11", 11);
People people2 = new People(2, "only-qi2", "12", 12);
People people3 = new People(3, "only-qi3", "14", 13);
People people4 = new People(1, "only-qi4", "14", 14);
People people5 = new People(2, "only-qi5", "13", 15);
People people6 = new People(1, "only-qi6", "11", 11);
ArrayList<People> arrayList = new ArrayList<>();
arrayList.add(people1);
arrayList.add(people2);
arrayList.add(people3);
arrayList.add(people4);
arrayList.add(people5);
arrayList.add(people6);
Map<String, List<People>> map = arrayList.stream().collect(Collectors.groupingBy(People::getAddress));
for (String s : map.keySet()) {
System.out.println("key值是:" + s + "=========" + "value的值是" + map.get(s));
}
}
测试结果:
2、Collections.groupingBy() 多字段分组
Map<String, List<People>> map1 = arrayList.stream().collect(Collectors.groupingBy(p->p.getAddress()+"#"+p.getAge()));
for (String s : map1.keySet()) {
System.out.println("key值是:" + s + "=========" + "value的值是" + map1.get(s));
}
测试结果: