选择列表中的元素,直到满足 Java 8 Lambda 条件

Picking elements of a list until condition is met with Java 8 Lambdas(选择列表中的元素,直到满足 Java 8 Lambda 条件)

本文介绍了选择列表中的元素,直到满足 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 条件

基础教程推荐