英文:
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<String> predicate) , which makes me unable to keep the whole stream, or mapping the stream somehow: Map<List<String> , Boolean>
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<String> stream = Stream.of("aaa", "aaaa", "aaaaaa");
stream
.map(str -> str.length() < 5 ? str + "-short" : str + "-long")
.forEach(System.out::println);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论