在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的功能。