opuser1
opuser1

Reputation: 477

Java8 convert list<P> in to Map<Integer, List<P>>

I have List<Person> object and would like to convert this in to Map<Integer, List<Person>> where the key of the map denotes a person's property grade. Its possible to have multiple Person object with the same grade in the source list, in that case i want to group them all in to List against the corresponding grade in the resulting Map.

I have the below code, so far

public class PersonMain
{
   public static void main(String[] args)
   {
    Person person1 = new Person();
    person1.setName("person1");
    person1.setGrade(1);

    Person person2 = new Person();
    person2.setName("person2");
    person2.setGrade(2);

    Person person3 = new Person();
    person3.setName("person3");
    person3.setGrade(1);

    List<Person> persons = Arrays.asList(person1, person2, person3);

    Map<Integer, List<Person>> personsMap = persons.stream()
            .collect(Collectors.toMap(Person::getGrade, PersonMain::getPerson, PersonMain::combinePerson));

    System.out.println(personsMap);
}
private static List<Person> getPerson(Person p)
{
    List<Person> persons = new ArrayList<>();
    persons.add(p);
    return persons;
}
private static List<Person> combinePerson(List<Person> oldVal, List<Person> newVal)
{
        oldVal.addAll(newVal);
        return oldVal;
    }
}

Is there a better way of implementing this?

Upvotes: 3

Views: 97

Answers (2)

Magd Kudama
Magd Kudama

Reputation: 3469

Much simpler solution if using Java 8:

Map<Integer, List<Person>> map = persons.stream()
    .collect(Collectors.groupingBy(Person::getGrade));

Upvotes: 1

Ousmane D.
Ousmane D.

Reputation: 56453

Your current solution is fine, but it's more intuitive to do it with the groupingBy collector:

Map<Integer, List<Person>> personsMap = 
        persons.stream()
                .collect(Collectors.groupingBy(Person::getGrade));

This overload of the groupingBy collector is pretty straightforward as all it does is take a classifier (Person::getGrade) function which will extract the key to group the objects of the stream by.

Upvotes: 5

Related Questions