Bala Bala -3 years ago 137
Java Question

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

I have a list of dto with following element.

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
and Value is List of

When I use

Map<Integer, List<UserBasicInfoDto>> superUserAcctMap =

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

Answer Source

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

Map<Integer, List<String>> result =
        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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download