using Java stream if a string is found then add to a list and also add an extra element

huangapple go评论74阅读模式
英文:

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&lt;String&gt; source = Arrays.asList(&quot;one&quot;, &quot;two&quot;, &quot;three&quot;);
    String s =&quot;Two-three-six-seven&quot;;

    List&lt;String&gt; 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&lt;String&gt; target = source.stream()
        .filter(s.toLowerCase()::contains)
        .collect(Collectors.collectingAndThen(Collectors.toList(),
                list -&gt; list.isEmpty() ? list : 
                        Stream.concat(list.stream(), Stream.of(&quot;number&quot;))
                                .collect(Collectors.toList())));

System.out.println(target);

Output

[two, three, number]

huangapple
  • 本文由 发表于 2020年10月21日 01:18:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/64450269.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定