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?