Ashish Ashish - 1 month ago 12
Java Question

Stream Filter with individual collect

I have list of persons & each person has person type ie 10, 11, 12

I want to make sublist which has each of person type

With Streams I have achieved this with 3 iterations

Can group & get in 1 iteration ?

Person.java

public class Person {

String personType;
String name;

public Person(String personType, String name) {
this.personType = personType;
this.name = name;
}

public String getPersonType() {
return personType;
}

public void setPersonType(String personType) {
this.personType = personType;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

@Override
public String toString() {
return "Person{" +
"personType='" + personType + '\'' +
", name='" + name + '\'' +
'}';
}
}


Driver.java

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class Driver {

public static void main(String[] args) {

List<Person> persons = populateList();

List<Person> persons1 = persons.stream().filter( p -> p.getPersonType().equals("10")).collect(Collectors.toList());
List<Person> persons2 = persons.stream().filter( p -> p.getPersonType().equals("10")).collect(Collectors.toList());
List<Person> persons3 = persons.stream().filter( p -> p.getPersonType().equals("10")).collect(Collectors.toList());

}
public static List<Person> populateList(){
Person person01 = new Person("10","Tony");
Person person02 = new Person("11","Steve");
Person person03 = new Person("12","Banner");
Person person04 = new Person("10","Thor");
Person person05 = new Person("11","Natasha");
Person person06 = new Person("12","Loki");
Person person07 = new Person("10","Peter");
Person person08 = new Person("11","HawkEye");
Person person09 = new Person("12","Falcon");
Person person10 = new Person("10","Jarvis");
List<Person> persons = new ArrayList<>();
persons.add(person01);
persons.add(person02);
persons.add(person03);
persons.add(person04);
persons.add(person05);
persons.add(person06);
persons.add(person07);
persons.add(person08);
persons.add(person09);
persons.add(person10);
return persons;
}
}

Answer

You can use group by.

Map<String, List<Person>> obj1 = persons.stream().collect(Collectors.groupingBy(Person :: getPersonType));
System.out.println(obj1);