Collectors.groupingBy 分组后对list实体类转换
时间: 2023-08-01 12:15:48
浏览: 984

数组和list相互转换
如果你想使用`Collectors.groupingBy`对一个list进行分组,并将每个分组的元素转换为另一个实体类,你可以使用`Collectors.mapping`来实现。下面是一个示例,假设我们有一个Person类和一个Student类,我们要按照年龄(age)对Person列表进行分组,并将每个分组的Person对象转换为Student对象:
```java
import java.util.[arraylist](https://wenku.csdn.net/doc/64520d70fcc53913680078c3?spm=1055.2569.3001.10083);
import java.util.List;
import java.util.Map;
import java.util.[stream](https://wenku.csdn.net/doc/6412b523be7fbd1778d42131?spm=1055.2569.3001.10083).Collectors;
[class](https://wenku.csdn.net/doc/2tcmm0ijyd?spm=1055.2569.3001.10083) Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
// getters and setters
class Student {
private String name;
private int age;
private String grade;
public Student(String name, int age, String grade) {
this.name = name;
this.age = age;
this.grade = grade;
// getters and setters
public class Main {
public static void main(String[] args) {
List<Person> persons = new ArrayList<>();
persons.add(new Person("Alice", 20));
persons.add(new Person("Bob", 22));
persons.add(new Person("Charlie", 20));
persons.add(new Person("David", 22));
Map<Integer, List<Student>> groupedStudents = persons.stream()
.collect(Collectors.groupingBy(Person::getAge,
Collectors.mapping(person -> new Student(person.getName(), person.getAge(), "A+"),
Collectors.toList())));
[system](https://wenku.csdn.net/doc/6412b784be7fbd1778d4a95f?spm=1055.2569.3001.10083).out.[print](https://wenku.csdn.net/doc/6401acb5cce7214c316ecd5e?spm=1055.2569.3001.10083)ln(groupedStudents);
在上述示例中,我们通过`Collectors.groupingBy`按照年龄将Person列表分组。在`Collectors.mapping`中,我们将每个Person对象转换为一个Student对象,并使用`Collectors.toList`将它们收集到一个列表中。最终,我们得到了一个以年龄为键,以Student列表为值的Map。
请注意,上述示例中的Person和Student类仅作为示例,你可以根据自己的实际需求定义和修改这两个类。
阅读全文
相关推荐
















