Reputation: 313
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?
Upvotes: 2
Views: 147
Reputation: 1463
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();
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));
}
}
Upvotes: 4
Reputation: 29680
If I were you, I'd stream the List
and use Collectors.partitioningBy
to collect it to a Map<Boolean, List<Person>>
where the males are true
(or false
), and the females are the opposite of the males. It's as simple as the following:
personList.stream()
.collect(Collectors.partitioningBy(person -> "male".equals(person.getGender())));
Printing this will return the following (after implementing Person#toString
):
{false=[Person [Name: Monica, Age: 30, Gender: female], Person [Name: Sophia, Age: 20, Gender: female], Person [Name: Carol, Age: 25, Gender: female]], true=[Person [Name: Adam, Age: 30, Gender: male], Person [Name: John, Age: 32, Gender: male]]}
Upvotes: 4