按谓词查找第一个元素 [英] Find first element by predicate

查看:118
本文介绍了按谓词查找第一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始玩Java 8 lambdas,我正在尝试实现一些我习惯使用的函数式语言。

I've just started playing with Java 8 lambdas and I'm trying to implement some of the things that I'm used to in functional languages.

For例如,大多数函数式语言都有某种类型的查找函数,这些函数在序列上运行,或者返回第一个元素的列表,谓词为 true 。我在Java 8中实现这一目标的唯一方法是:

For example, most functional languages have some kind of find function that operates on sequences, or lists that returns the first element, for which the predicate is true. The only way I can see to achieve this in Java 8 is:

lst.stream()
    .filter(x -> x > 5)
    .findFirst()

然而这似乎效率低下对我来说,因为过滤器会扫描整个列表,至少根据我的理解(这可能是错误的)。有没有更好的办法?

However this seems inefficient to me, as the filter will scan the whole list, at least to my understanding (which could be wrong). Is there a better way?

推荐答案

不,过滤器不扫描整个流。这是一个中间操作,它返回一个惰性流(实际上所有中间操作都返回一个惰性流)。为了说服你,你可以简单地做以下测试:

No, filter does not scan the whole stream. It's an intermediate operation, which returns a lazy stream (actually all intermediate operations return a lazy stream). To convince you, you can simply do the following test:

List<Integer> list = Arrays.asList(1, 10, 3, 7, 5);
int a = list.stream()
            .peek(num -> System.out.println("will filter " + num))
            .filter(x -> x > 5)
            .findFirst()
            .get();
System.out.println(a);

哪些输出:

will filter 1
will filter 10
10

你看到只有流的两个第一个元素才被实际处理。

You see that only the two first elements of the stream are actually processed.

所以你可以选择你的方法,这完全没问题。

So you can go with your approach which is perfectly fine.

这篇关于按谓词查找第一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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