freitas :
I've been searching around and I couldnt find a smart way of doing a split of a list.
Let's say we have the following example:
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
}
So then I have:
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"));
Is there a way that I could generate two new lists of Person using Stream API grouping male and female?
J.Adler :
Sorry for the brevity, but I'm on the train going home.
Map<String, List<Person>> map = list.stream()
.collect(Collectors.groupingBy(Person::getGender));
And the code
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));
}
}