5

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.

1

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Collectors.mapping(obj -> obj, toList()) didn't work for me.
2

You can try this:

customerSuperUserList.stream().collect(Collectors.groupingBy(UserBasicInfoDto::getUserSeqId,Collectors.mapping(UserBasicInfoDto::getAcctAgencyNumber, Collectors.toList())));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.