gpt4 book ai didi

java - 从列表生成列表

转载 作者:行者123 更新时间:2023-12-01 05:41:08 24 4
gpt4 key购买 nike

我一直在四处寻找,但找不到一种拆分列表的聪明方法。

假设我们有以下示例:

public class Person {
private String name;
private int age;
private String gender;

public Person(String name, int age, String gender) {
this.name = name;
this.age = age;
this.gender = gender;
}

// Getters/setters
}

那么我有:

List<Person> personList = new ArrayList<>();
personList.add(new Person("Adam", 30, "male"));
personList.add(new Person("John", 32, "male"));
personList.add(new Person("Monica", 30, "female"));
personList.add(new Person("Sophia", 20, "female"));
personList.add(new Person("Carol", 25, "female"));

有没有一种方法可以使用 Stream API 将男性和女性分组生成两个新的人员列表?

最佳答案

抱歉这么短,但我正在回家的火车上。

Map<String, List<Person>> map = list.stream()
.collect(Collectors.groupingBy(Person::getGender));

代码

public class Person {
private String name;
private int age;
private String genre;

public Person(String name, int age, String genre) {
this.name = name;
this.age = age;
this.genre = genre;
}

// getters and setters
}

public class GroupBy {

public static void main(String[] args) {

List<Person> list = ArrayList();

list.add(new Person("Adam", 30, male));
list.add(new Person("John", 32, male));
list.add(new Person("Monica", 30, female));
list.add(new Person("Sophia", 20, female));
list.add(new Person("Carol", 25, female));

Map<String, List<Person>> map = list.stream()
.collect(Collectors.groupingBy(Person::getGender));
}
}

关于java - 从列表生成列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52487994/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com