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 条件
基础教程推荐
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 降序排序:Java Map 2022-01-01