Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 Lambda List to Map<Int, List<String>>

Tags:

java

lambda

I have a list of dto with following element. userSeqId have duplicate values,

private int userSeqId;
private String firstName;
private String lastName;
private String acctAgencyNumber;

I am trying to use Java 8 Lambda to group by 'userSeqId' to a Map.

I want Map<Integer, List<String>> where Key should be userSeqId and Value is List of acctAgencyNumber.

When I use

Map<Integer, List<UserBasicInfoDto>> superUserAcctMap = customerSuperUserList.stream()
    .collect(Collectors.groupingBy(UserBasicInfoDto::getUserSeqId));

I get Map<Integer, List<UserBasicInfoDto>> where key is userSeqId but value is list of whole object.

like image 220
Bala Avatar asked Aug 15 '17 16:08

Bala


People also ask

Can we convert list to map in Java?

With Java 8, you can convert a List to Map in one line using the stream() and Collectors. toMap() utility methods. The Collectors. toMap() method collects a stream as a Map and uses its arguments to decide what key/value to use.

How do I find a list of values on a map?

Since the map contains a key, value pair, we need two lists to store each of them, namely keyList for keys and valueList for values. We used map's keySet() method to get all the keys and created an ArrayList keyList from them.


1 Answers

There is a dedicated version of groupingBy() for your use case:

Map<Integer, List<String>> result = customerSuperUserList.stream()
      .collect(Collectors.groupingBy(
        UserBasicInfoDto::getUserSeqId,
        Collectors.mapping(UserBasicInfoDto::getAcctAgencyNumber, toList())));

The key point of this is to use the helper mapping collector, using which you can override the default groupingBy behaviour.

like image 153
Grzegorz Piwowarek Avatar answered Oct 02 '22 10:10

Grzegorz Piwowarek