I have a List
object and want to convert it Map<Integer, List>
into a map key representing a person’s property level .It may be possible to have multiple Person objects with the same rank in the source list, in which case I want to group them all into a List, corresponding to the corresponding rank in the generated Map.
So far I have the following code
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 persOns= Arrays.asList(person1, person2, person3); Map<Integer, List> persOnsMap= persons.stream() .collect(Collectors.toMap(Person::getGrade, PersonMain::getPerson, PersonMain::combinePerson)); System.out.println(personsMap); } private static List getPerson(Person p) { List persOns= new ArrayList(); persons.add(p); return persons; } private static List combinePerson(List oldVal, List newVal) { oldVal.addAll(newVal); return oldVal; } }
Is there a better way to achieve this?
1> Ousmane D…:
Your current solution is good, but using the groupingBy collector is more intuitive:
Map<Integer, List> persOnsMap= persons.stream() .collect(Collectors.groupingBy(Person::getGrade));
This overload of the groupingBy
collector is very simple as it only requires a classifier (Person::getGrade)
function which will extract the key Group objects of a stream.