[英]How to map List<String> where each string is a comma separated strings to List<String> split on commas joined?
tags -- ["tag1", "tag2, tag3"]
标签 --
["tag1", "tag2, tag3"]
expected output -- ["tag1","tag2","tag3"]
预期 output --
["tag1","tag2","tag3"]
Current code:当前代码:
List<String> tagsProcessed = new ArrayList<>();
for(String t : tags) {
tagsProcessed.addAll(Stream.of(t.split(",")).map(String::trim).collect(Collectors.toList()));
}
How to rewrite it with streams?如何用流重写它?
one solution of many:许多解决方案之一:
var delimiter = Pattern.compile(",");
tags.stream()
.flatMap(delimiter::splitAsStream)
.map(String::trim)
.forEach(tagsProcessed::add);
or, avoiding (hiding!) the trim
call (but without removing white spaces at start and end of input strings):或者,避免(隐藏!)
trim
调用(但不删除输入字符串开头和结尾的空格):
var delimiter = Pattern.compile("\\s*,\\s*");
tags.stream()
.flatMap(delimiter::splitAsStream)
.forEach(tagsProcessed::add);
I prefer first one, clearly showing the call to trim
我更喜欢第一个,清楚地显示
trim
的调用
all the above can also be changed to (directly) use the result of Collectors.toList()
, but beware of kind of returned List
.以上所有内容也可以更改为(直接)使用
Collectors.toList()
的结果,但要注意返回的List
类型。 From documentation:从文档:
There are no guarantees on the type, mutability, serializability, or thread-safety of the List returned;
不保证返回的 List 的类型、可变性、可序列化性或线程安全性; if more control over the returned List is required, use toCollection(Supplier).
如果需要对返回的列表进行更多控制,请使用 toCollection(Supplier)。
Using it with addAll
is not a problem (but similar to using forEach
as in above code);将它与
addAll
一起使用不是问题(但类似于在上面的代码中使用forEach
); also not a problem if the returned list is not being changed.如果返回的列表没有被更改,也不是问题。
Use flatMap
, which can map one element to any number of elements, represented as a stream.使用
flatMap
,它可以 map 一个元素到任意数量的元素,表示为 stream。 In this case, we map each tag to the array of tags produced by split
.在这种情况下,我们将 map 每个标签分配到
split
生成的标签数组中。
List<String> tagsProcessed = tags.stream()
.flatMap(tag -> Arrays.stream(tag.split(", ")))
.collect(Collectors.toList());
You can also use:您还可以使用:
List<String> tagsProcessed = tags.stream()
.map(s -> s.trim().split(",\\s*"))
.flatMap(Arrays::stream)
.collect(Collectors.toList());
List<String> tags = Arrays.asList("1 ,2 ,3 ,4 ", "5 ,6 ,7 ,8 ", " 9, 10");
List<String> tagsProcessed =
tags.stream() //Stream the list of String as is
.flatMap(tag -> Arrays.stream(tag.split(","))) // flatMap to avoid Stream<Stream<String>>, this produces Stream<String>
.map(String::trim) //trim as in requirement
.collect(Collectors.toList());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.