数据库中有groupby 分组,Java里面其实也有的,感觉很好用。对List里面的数据进行分组,一行代码解决问题,太爽了
话不多说,上代码。
people实体:按照人员的地址分组,使用map<key,List<people>>接收。
public 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 +
'}';
}
}
实例方法:
public class Test {
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",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));
}
}
}
执行结果:
|