フレイタス:
私は周りに検索してきたと私は、リストの分割を行うためのスマートな方法を見つけるcouldntの。
我々は、次の例があるとしましょう:
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"));
私は男性と女性のグループ化ストリームAPIを使用している人の二つの新しいリストを生成することができること方法はありますか?
J.Adler:
簡潔にするために申し訳ありませんが、私は家に行く電車のです。
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();
liist.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));
}
}