Java streams to split and collect string to a Map [duplicate]

穿精又带淫゛_ 提交于 2019-12-19 13:35:54

问题


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"


回答1:


First split the with space as 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(" "));


来源:https://stackoverflow.com/questions/59362949/java-streams-to-split-and-collect-string-to-a-map

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!