英文:
using Java stream if a string is found then add to a list and also add an extra element
问题
使用流,我希望在找到匹配的字符串时填充一个字符串数组,然后将一个新的字符串添加到数组中。
例如,这段代码将返回一个列表:
List<String> source = Arrays.asList("one", "two", "three");
String s = "Two-three-six-seven";
List<String> target = source.stream()
.filter(s.toLowerCase()::contains)
.collect(Collectors.toList());
创建了一个包含 "two" 和 "three" 的列表(target)。
现在,我该如何检查目标列表是否有值,然后添加另一个值,比如 "numbers",以便最终得到一个包含 "two"、"three" 和 "numbers" 的列表?
我知道可以通过在流之外添加更多代码来实现,但我想尝试在流内部完成所有操作。
英文:
using streams i want to populate a string array if a match is found with the matching strings and then add a new string to the array.
example this code will return a list:
List<String> source = Arrays.asList("one", "two", "three");
String s ="Two-three-six-seven";
List<String> target = source.stream()
.filter(s.toLowerCase()::contains)
.collect(Collectors.toList());
}
creates a list (target) with "two" and "three" in it.
how can i now check that if the target list has a value then i add another value e.g. "numbers"
ending up with a list that has "two" "three" and "numbers"
I know this is possible by adding more code outside of the stream but I am trying to do all inside the stream
答案1
得分: 1
正如@Charlie Armstrong在上面评论中提到的那样,这不是对Stream
的良好使用方式。但是,如果由于任何原因您仍然必须使用Stream
,您可以使用Collectors.collectingAndThen()
:
List<String> target = source.stream()
.filter(s.toLowerCase()::contains)
.collect(Collectors.collectingAndThen(Collectors.toList(),
list -> list.isEmpty() ? list :
Stream.concat(list.stream(), Stream.of("number"))
.collect(Collectors.toList())));
System.out.println(target);
输出
[two, three, number]
英文:
As @Charlie Armstrong commented above, thats not a good use of a Stream
.
However, if you still have to use a Stream
for any reason, you can use Collectors.collectingAndThen()
:
List<String> target = source.stream()
.filter(s.toLowerCase()::contains)
.collect(Collectors.collectingAndThen(Collectors.toList(),
list -> list.isEmpty() ? list :
Stream.concat(list.stream(), Stream.of("number"))
.collect(Collectors.toList())));
System.out.println(target);
Output
[two, three, number]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论