Java8 convert List to Map<Integer,List>

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.

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/java8-convert-list-to-mapintegerlist/

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: 34331943@QQ.com

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索