Picking elements of a list until condition is met with Java 8 Lambdas(选择列表中的元素,直到满足 Java 8 Lambda 条件)
问题描述
我正试图将我的想法转变为思考功能性方式,并且最近遇到了一种情况,我需要从列表中挑选元素直到满足条件,而我找不到一种简单自然的方式来实现这一点.显然我还在学习.
I am trying to switch my mind to think the functional way and recently faced a situation in which I needed to pick up elements from a list until a condition is met and I could not find an easy natural way of achieving this. Obviously I am still learning.
假设我有这个清单:
List<String> tokens = Arrays.asList("pick me", "Pick me", "pick Me",
"PICK ME", "pick me and STOP", "pick me", "pick me and Stop", "pick me");
// In a non lambdas was you would do it like below
List<String> myTokens = new ArrayList<>();
for (String token : tokens) {
myTokens.add(token);
if (token.toUpperCase().endsWith("STOP")) {
break;
}
}
提前感谢您的意见
注意:在发布此之前,我阅读了 通过谓词限制流,但我看不出如何使该答案适应我的问题.任何帮助将不胜感激.
NOTE: Before publishing this I read Limit a stream by a predicate but I could not see how I can adapt that answer to my problem. Any help would be appreciated thanks.
推荐答案
一个选项使用一个需要两个函数的收集器,一个将字符串添加到列表中,另一个将之前可能并行创建的列表组合起来.仅当先前的部分输出不以以 STOP 结尾的元素结尾时,它才添加字符串或整个列表:
One option uses a collector requiring two functions one that adds strings to lists and another which combines lists previously potentially created in parallel. For each it adds the string or the whole list only if the previous partial output doesn't end with an element that that ends with STOP:
tokens.stream().collect(() -> new ArrayList<String>(), (l, e) -> {
if(l.isEmpty() || !l.get(l.size()-1).toUpperCase().endsWith("STOP"))
l.add(e);
}, (l1, l2) -> {
if(l1.isEmpty() || !l1.get(l1.size()-1).toUpperCase().endsWith("STOP"))
l1.addAll(l2);
});
这篇关于选择列表中的元素,直到满足 Java 8 Lambda 条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:选择列表中的元素,直到满足 Java 8 Lambda 条件
- Jersey REST 客户端:发布多部分数据 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01