概述,使用java8的 stream groupingBy ,實作對list中的資料按照年齡對person對象的分組
1.Person
package com.qimh.springbootfiledemo;
public class Person {
private Integer age;
private String name;
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Person{" +
"age=" + age +
", name='" + name + '\'' +
'}';
}
}
2.測試方法
package com.qimh.springbootfiledemo;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class MainTest {
public static void testStreamCollect(){
List persons = new ArrayList<>();//Arrays.asList();
Person person = new Person();
person.setAge(20);
person.setName("張三");
Person person2 = new Person();
person2.setAge(20);
person2.setName("李四");
Person person3 = new Person();
person3.setAge(20);
person3.setName("王五");
persons.add(person);
persons.add(person2);
persons.add(person3);
Person person4 = new Person();
person4.setAge(21);
person4.setName("王八");
persons.add(person4);
Map> callRecordMap = persons.stream().collect(Collectors.groupingBy(Person::getAge));
for (Map.Entry> entry:callRecordMap.entrySet()){
Integer age = entry.getKey();
List personss = entry.getValue();
System.out.println("age:"+age);
System.out.println("personss:"+personss);
}
}
public static void main(String[] args){
testStreamCollect();
}
}
3.結果
age:20
personss:[Person{age=20, name='張三'}, Person{age=20, name='李四'}, Person{age=20, name='王五'}]
age:21
personss:[Person{age=21, name='王八'}]
參考連接配接:
https://cloud.tencent.com/developer/article/1187833 (下)
對流知識補充的連接配接:
https://cloud.tencent.com/developer/article/1187831 (上)