stream 分组

在Java中,使用Stream API可以对集合进行分组操作。以下是一些常见的分组示例:

  1. 按年龄分组
    List<Teacher> teacherList = new ArrayList<>();
    teacherList.add(new Teacher(1L, "张三", 20));
    teacherList.add(new Teacher(2L, "张三", 23));
    teacherList.add(new Teacher(3L, "李四", 21));
    teacherList.add(new Teacher(4L, "王五", 21));
    teacherList.add(new Teacher(5L, "赵六", 24));

    Map<Integer, List<Teacher>> groupTeacherMap = teacherList.stream()
            .collect(Collectors.groupingBy(Teacher::getAge));
    System.out.println(groupTeacherMap.get(21));
    // 输出: [Teacher(id=3, name=李四, age=21), Teacher(id=4, name=王五, age=21)]
    ```

2. **按多个属性分组** <b class="card40_249__sup_a7f6" data-sup="sup">3</b>:

```java
    List<Student> studentList = new ArrayList<>();
    studentList.add(new Student("张三", 85, 20));
    studentList.add(new Student("李四", 90, 21));
    studentList.add(new Student("王五", 78, 21));
    studentList.add(new Student("赵六", 92, 22));

    Map<Integer, List<Student>> groupStudentMap = studentList.stream()
            .collect(Collectors.groupingBy(Student::getAge, Collectors.groupingBy(Student::getName)));
    System.out.println(groupStudentMap.get(21));
    // 输出: {21=[Student(name=李四, score=90, age=21), Student(name=王五, score=78, age=21)]}
    ```

3. **按属性进行多条件分组** <b class="card40_249__sup_a7f6" data-sup="sup">1</b>:

```java
    List<Employee> employeeList = new ArrayList<>();
    employeeList.add(new Employee("张三", "北京", 1000));
    employeeList.add(new Employee("李四", "上海", 2000));
    employeeList.add(new Employee("王五", "北京", 1500));
    employeeList.add(new Employee("赵六", "深圳", 1200));

    Map<String, List<Employee>> groupEmployeeMap = employeeList.stream()
            .collect(Collectors.groupingBy(Employee::getCity, Collectors.groupingBy(Employee::getSales)));
    System.out.println(groupEmployeeMap.get("北京"));
    // 输出: [Employee(name=张三, city=北京, sales=1000), Employee(name=王五, city=北京, sales=1500)]
    ```

4. **根据对象属性进行分组并获取最大值** :

```java
    List<PdinfoSupplier> supplierList = new ArrayList<>();
    supplierList.add(new PdinfoSupplier(1, "A", 100));
    supplierList.add(new PdinfoSupplier(2, "B", 200));
    supplierList.add(new PdinfoSupplier(3, "A", 150));

    Map<String, PdinfoSupplier> groupSupplierMap = supplierList.stream()
            .collect(Collectors.groupingBy(PdinfoSupplier::getAccount,
                    Collectors.collectingAndThen(Collectors.maxBy(Comparator.comparingInt(PdinfoSupplier::getId)), Optional::get)));
    System.out.println(groupSupplierMap.get("A"));
    // 输出: PdinfoSupplier(id=3, account=A, id=150)
    ```

这些示例展示了如何使用Java Stream API进行分组操作,包括按单个属性分组和按多个属性分组。通过`Collectors.groupingBy()`方法,可以灵活地对集合数据进行分类和分析<b class="card40_249__sup_a7f6" data-sup="sup">1</b>。
Top