繁体   English   中英

Java 流将字符串拆分和收集到 Map

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

我有一个这样的字符串

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

我想创建一个看起来像的地图(过滤掉 label3} label1 -> {abc,xyz} label2 -> {cde,pqr} label3 -> {mno}

这是我目前能做的

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

还有第二个用例:我如何只收集一个字符串中的所有令牌

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

先用空格分割作为分隔符

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

然后用管道\\作为分隔符分割数组中的每个字符串并使用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())));

输出 :

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

使用Collectors.joiningMap值收集到 String 中

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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