在Java中,使用Stream API进行分组并收集某个属性到List中是一种常见的操作。这可以通过Collectors.groupingBy和Collectors.mapping结合使用来实现。下面是一个具体的示例:
假设我们有一个Person类,其中包含name和age属性,我们想要根据age属性对Person对象进行分组,并将每个组中的name属性收集到一个List中。
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;public class Person {private String name;private int age;// 构造函数、getter 和 setter 省略public Person(String name, int age) {this.name = name;this.age = age;}public String getName() {return name;}public int getAge() {return age;}
}// 某个地方在业务逻辑中使用Stream API进行分组
import java.util.Arrays;public class GroupingExample {public static void main(String[] args) {List<Person> people = Arrays.asList(new Person("zhangsan", 30),new Person("lisi", 30),new Person("wangwu", 25),new Person("zhaoliu", 25),new Person("tianqi", 30));Map<Integer, List<String>> peopleByAge = people.stream().collect(Collectors.groupingBy(Person::getAge, // 分组的键Collectors.mapping(Person::getName, Collectors.toList()) // 将name属性收集到List中));peopleByAge.forEach((age, names) -> {System.out.println("Age: " + age);names.forEach(name -> System.out.println("\t" + name));});}
}
在这个例子中:
people.stream():将people列表转换为流。Collectors.groupingBy(Person::getAge):根据Person对象的age属性进行分组。Collectors.mapping(Person::getName, Collectors.toList()):对于每个分组,将Person对象的name属性映射并收集到一个List中。
最终,peopleByAge是一个Map,其键是年龄,值是对应年龄的name列表。使用forEach打印出每个年龄组及其对应的名称列表。
这种方法是处理集合分组和属性收集的非常强大且表达式的方式,充分利用了Java 8及以上版本的Stream API的功能。