Java流可将字符串拆分并收集到Map [英] 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";
我想创建一个看起来像(过滤掉label3之后)的地图label1-> {abc,xyz}label2-> {cde,pqr}label3-> {mno}
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 xyzmno pqr"
abc|label1 cde|label2 xyz|label1 mno|label3 pqr|label2 => "abc cde xyz mno pqr"
推荐答案
首先用空格分隔
作为分隔符
First split the with space as delimiter
input.split(" ") //[abc|label1, cde|label2, xyz|label1, mno|label3, pqr|label2]
然后使用管道 \
作为分隔符分割数组中的每个字符串,并使用 Collectors.groupingBy
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())));
输出:
{label1=[abc, xyz], label2=[cde, pqr], label3=[mno]}
使用 Collectors.joining
将值从 Map
收集到String
Use Collectors.joining
to collect value from Map
into String
String result = map.values()
.stream()
.flatMap(Collection::stream)
.collect(Collectors.joining(" "));
这篇关于Java流可将字符串拆分并收集到Map的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!