How to convert List of Objects to map using object's fields in Java

yateen :

I have Following use case:

    User Object is as followed:
    UserId      payload
    123         abc1
    123         abc2
    456         pqr1
    456         pqr2
    678         xyz1

And after iterating above list<User Object>, Result should be like: 
{123=[abc1, abc2], 456=[pqr1,pqr2], 678=[xyz1]}

so that I can use value(list of other objects) for key(123) for further processing. What will be best way to do it?

I have tried below but not sure how performance efficient if object size increases.

Map<String,List<String>> userMap = new HashMap<String, List<String>>();     
for(User user: users) {
  String userId = user.getUserId();
  List<String> payloads = new ArrayList<String>();
  if(userMap.containsKey(userId)) {
      payload = userMap.get(userId);
                  payloads.add(user.getPayload());
      userMap.put(userId, payloads);
  }
  else {
      payloads.add(user.getPayload());
      userMap.put(user.getUserId(), payloads);
  }
 }
Jacob G. :

The easiest way would be to stream the List and use Collectors#groupingBy and Collectors#mapping:

Map<String, List<String>> userMap = users.stream()
    .collect(Collectors.groupingBy(User::getUserId, 
        Collectors.mapping(User::getPayload, Collectors.toList())));

Output:

{123=[abc1, abc2], 456=[pqr1, pqr2], 678=[xyz1]}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=310798&siteId=1