3

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?

utkusonmez
  • 1,486
  • 15
  • 22
opuser1
  • 427
  • 7
  • 29

2 Answers2

5

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.

Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
1

Much simpler solution if using Java 8:

Map<Integer, List<Person>> map = persons.stream()
    .collect(Collectors.groupingBy(Person::getGrade));
Oleksandr Pyrohov
  • 14,685
  • 6
  • 61
  • 90
Magd Kudama
  • 3,229
  • 2
  • 21
  • 25