简体   繁体   中英

Java streams to split and collect string to a Map

I have a string like this

String input = "abc|label1 cde|label2 xyz|label1 mno|label3 pqr|label2";

I want to create a Map which looks like (after filtering out label3} label1 -> {abc,xyz} label2 -> {cde,pqr} label3 -> {mno}

This is what I could do so far

  Map<String, List<String>> result = Arrays.stream(inputString.split(" "))
                .filter(i -> !i.contains("label3"))
                .map(i -> i.split("//|"))

Also second use case: how do I just collect the tokens all in one string

abc|label1 cde|label2 xyz|label1 mno|label3 pqr|label2 => "abc cde xyz mno pqr"

First split the with spaceas delimiter

input.split(" ") //[abc|label1, cde|label2, xyz|label1, mno|label3, pqr|label2]

And then split each string in array with pipe \\ as delimiter and use Collectors.groupingBy

Map<String, List<String>> map = Arrays.stream(input.split(" "))
                                      .map(s -> s.split("\\|"))
                                      .collect(Collectors.groupingBy(str -> str[1], 
                                             Collectors.mapping(str -> str[0], Collectors.toList())));

Output :

{label1=[abc, xyz], label2=[cde, pqr], label3=[mno]}

Use Collectors.joining to collect value from Map into String

String result = map.values()
                   .stream()
                   .flatMap(Collection::stream)
                   .collect(Collectors.joining(" "));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM