- 定義實體類
public class Person {
public Integer id;
public String name;
public Integer age;
public Person(){}
public Person(Integer id, Integer age, String name){
this.id = id;
this.age = age;
this.name = name;
}
@Override
public String toString(){
return id + "," + age + "," + name;
}
}
- 構造數據
private static List<Person> getList(){
List<Person> personList = new ArrayList<>();
personList.add(new Person(1, 10, "王1"));
personList.add(new Person(2, 10, "王2"));
personList.add(new Person(3, 12, "王3"));
personList.add(new Person(4, 14, "張1"));
personList.add(new Person(5, 8, "張2"));
personList.add(new Person(6, 6, "張3"));
personList.add(new Person(7, 8, "李1"));
personList.add(new Person(8, 15, "李2"));
personList.add(new Person(9, 20, "何何何"));
personList.add(new Person(10, 16, "李3"));
return personList;
}
- 分組查詢(按姓氏進行分組)
public static void main( String[] args )
{
List<Person> list = getList();
Map<String, List<Person>> collect = list.stream().collect(Collectors.groupingBy(p -> p.name.substring(0, 1), Collectors.toList()));
System.out.println(collect);
}
- 結果如下:
{張=[4,14,張1, 5,8,張2, 6,6,張3], 何=[9,20,何何何], 王=[1,10,王1, 2,10,王2, 3,12,王3], 李=[7,8,李1, 8,15,李2, 10,16,李3]}