我有一个
List<Person>
。使用 Java 流,我可以使用如下方式按姓氏对人员进行分组:
Map<String, List<Person>> persons.stream()
.collect(Collectors.groupingBy(Person::getLastName));
但是如果我想按姓氏对人员的“名字”进行分组怎么办?换句话说,按姓氏“Smith”分组,我可能有一个“Jane”和“John”的列表。我可以使用 groupingBy()
的值提取器版本吗?我在想这样的事情:
Map<String, List<String>> persons.stream()
.collect(Collectors.groupingBy(Person::getLastName, Person::getFirstName));
Collectors.mapping()
方法中使用
Collectors.groupingBy()
作为下游收集器:import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
class Main {
public static void main(String[] args) {
List<Person> persons = List.of(
new Person("Smith", "John"),
new Person("Doe", "Jane"),
new Person("Smith", "Alex"),
new Person("Doe", "John"),
new Person("Brown", "Charlie")
);
Map<String, List<String>> groupedByLastName = persons.stream()
.collect(Collectors.groupingBy(
Person::getLastName,
Collectors.mapping(Person::getFirstName, Collectors.toList())
));
System.out.println(groupedByLastName);
}
}
class Person {
private String lastName;
private String firstName;
public Person(String lastName, String firstName) {
this.lastName = lastName;
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public String getFirstName() {
return firstName;
}
@Override
public String toString() {
return "Person{lastName='" + lastName + "', firstName='" + firstName + "'}";
}
}
输出:
{Brown=[Charlie], Smith=[John, Alex], Doe=[Jane, John]}