Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
264 views
in Technique[技术] by (71.8m points)

java - 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.

question from:https://stackoverflow.com/questions/66055002/how-to-split-a-string-into-a-map-grouping-values-by-duplicate-keys-using-stream

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...