有没有办法根据一个谓词在流中执行中间操作?

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

Is there any way to execute intermediate operations in a stream depending on a Predicate?

问题

问题听起来显而易见,但我尚未找到可以根据谓词在流上执行的任何中间操作。例如,想象我们有一个字符串流,如果字符串少于5个字符,我们希望将"-short"附加到字符串,否则附加"-long"。

问题在于,据我所知,我被迫应用.filter(Predicate<String> predicate),这使我无法保留整个流,或者以某种方式映射流:Map<List<String>, Boolean>

是否有任何方法可以根据谓词或某些条件结构执行此类操作?

英文:

The question may sound way obvious, but I haven't been able to find any intermediate operations that executes on a stream depending on a Predicate. For instance, imagine we have a stream of String and we want to append "-short" to the string if it has less than 5 characters and "-long" otherwise.

The thing is that, as far as I know, I'm forced to apply .filter(Predicate&lt;String&gt; predicate) , which makes me unable to keep the whole stream, or mapping the stream somehow: Map&lt;List&lt;String&gt; , Boolean&gt;

Is there any way I can execute such operations depending on Predicate or some conditional structure?

答案1

得分: 2

你可以通过使映射函数本身根据条件返回不同的结果来实现这一点。

Stream<String> stream = Stream.of("aaa", "aaaa", "aaaaaa");
stream
    .map(str -> str.length() < 5 ? str + "-short" : str + "-long")
    .forEach(System.out::println);
英文:

You can achieve that by making the mapping function itself return different result based on a condition.

Stream&lt;String&gt; stream = Stream.of(&quot;aaa&quot;, &quot;aaaa&quot;, &quot;aaaaaa&quot;);
stream
    .map(str -&gt; str.length() &lt; 5 ? str + &quot;-short&quot; : str + &quot;-long&quot;)
    .forEach(System.out::println);

huangapple
  • 本文由 发表于 2023年2月24日 00:35:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/75547710.html
匿名

发表评论

匿名网友

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

确定