Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a string into a map, grouping values by duplicate keys using streams?

I want to convert the following

String flString="view1:filedname11,view1:filedname12,view2:fieldname21";

to a Map<String,Set<String>> to get the key/value as below:

view1=[filedname11,filedname12]
view2=[fieldname21]

I want to use Java 8 streams. I tried

Arrays.stream(tokens)
        .map(a -> a.split(":"))
        .collect(Collectors.groupingBy(
                a -> a[0], Collectors.toList()));

However the keys are also getting added to the value list.

like image 859
TAugusti Avatar asked Jun 05 '26 23:06

TAugusti


1 Answers

You should use a Collectors::mapping to map the array to an element.

String flString = "view1:filedname11,view1:filedname12,view2:fieldname21";

Map<String, List<String>> map = Pattern.compile(",")
    .splitAsStream(flString)
    .map(a -> a.split(":"))
    .collect(
        Collectors.groupingBy(a -> a[0],
            Collectors.mapping(a -> a[1], Collectors.toList())
        )
    );

map.entrySet().forEach(System.out::println);

Output

view1=[filedname11, filedname12]
view2=[fieldname21]
like image 68
K.Nicholas Avatar answered Jun 07 '26 11:06

K.Nicholas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!