Java中对List数据进行分组的例子
例:在实体类people中,按照人员的地址分组,使用map<key,List<people>>接收。
package com.felix;
import com.cars.ict.rbpsems.RbpsemsWebApplication;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = RbpsemsWebApplication.class)
public class CollectorsGroupingBy {
@Test
public void groupingTest() {
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", 16);
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));
}
}
}
class People {
private Integer id;
private String name;
private String address;
private Integer age;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public People() {
}
public People(Integer id, String name, String address, Integer age) {
this.id = id;
this.name = name;
this.address = address;
this.age = age;
}
@Override
public String toString() {
return "People{" +
"id=" + id +
", name='" + name + '\'' +
", address='" + address + '\'' +
", age=" + age +
'}';
}
}
结果如下:

也可以按照多个字段进行分组:
Map<String, List<People>> collect = arrayList.stream().collect(Collectors.groupingBy(p -> p.getAddress() + "_" + p.getId()));
for(String s : collect.keySet()) {
System.out.println("key的值是:" + s + "=============" + "value的值是:" + collect.get(s));
}
结果如下:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 记一次.NET内存居高不下排查解决与启示
2021-08-10 Arrays.asList();
2021-08-10 idea一条插入语句执行后,数据库出现两条一样的该数据