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

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

问题描述

我刚刚开始使用 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.

例如,大多数函数式语言都有某种对序列或返回第一个元素的列表进行操作的 find 函数,其谓词为 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天全站免登陆