选择列表的元素直到条件满足 Java 8 Lambda [英] Picking elements of a list until condition is met with Java 8 Lambdas

查看:25
本文介绍了选择列表的元素直到条件满足 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆