yateen
yateen

Reputation: 85

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

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);
  }
 }

Upvotes: 1

Views: 1277

Answers (2)

Jacob G.
Jacob G.

Reputation: 29680

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]}

Upvotes: 5

twobiers
twobiers

Reputation: 1298

Another possible solution would be to use Guavas Maps.toMap

Upvotes: 0

Related Questions