Java8使用stream對List列表分組


  1. 定義實體類
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;
    }
}
  1. 構造數據
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;
}
  1. 分組查詢(按姓氏進行分組)
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);
}
  1. 結果如下:
{=[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]}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM