Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 Stream group by and concatenate strings using a separator

Tags:

java

java-8

I have list of objects which consists of bankId, IdentifierId and IdentifierValue. For each bank I have more than one identifierValue. My requirement is to create a map by grouping the List based on bankId and concate the identifierValue into a single string separated by /.

eg:

Bank of America, identifer-1,  123
Bank of America, identifer-2,  234
wells Forgo,     identifier-1, 123

I want the result to be a map like below

bank of America -> 123/234
wellsForgo -> 123

Class:

public class BankIdentifier {
    private String bankId;
    private String identifierId;
    private String identifierValue;
}

I am using Java 8 Streams groupby, but I am not able to get the identifier value separated by /

like image 934
rroy Avatar asked Jan 04 '23 06:01

rroy


1 Answers

This would group the list based on bankId and the identifierValue accumulated into a single string separated by / delimiter.

Map<String, String> result =
                items.stream().collect(
                        Collectors.groupingBy(BankIdentifier::getBankId,
                                Collectors.mapping(BankIdentifier::getIdentifierValue, Collectors.joining("/")))
                        );

Ensure that you have a getter for bankId and identifierValue in order to use the method reference syntax.

like image 170
Ousmane D. Avatar answered Jan 13 '23 17:01

Ousmane D.