本文翻译自:Find first element by predicate

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. 我刚刚开始使用Java 8 lambda,并且正在尝试实现一些我在函数式语言中惯用的东西。

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 . 例如,大多数功能语言都具有某种对序列进行操作的find函数,或者对返回谓词为true的第一个元素的列表进行操作。 The only way I can see to achieve this in Java 8 is: 我看到的在Java 8中实现此目标的唯一方法是:

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? 有没有更好的办法?


#1楼

参考:https://stackoom.com/question/1bQUf/通过谓词查找第一个元素


#2楼

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);

Which outputs: 哪个输出:

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. 因此,您可以采用完全正确的方法。


#3楼

However this seems inefficient to me, as the filter will scan the whole list 但是这对我来说似乎效率低下,因为过滤器将扫描整个列表

No it won't - it will "break" as soon as the first element satisfying the predicate is found. 不,它不会-一旦找到满足谓词的第一个元素,它就会“中断”。 You can read more about laziness in the stream package javadoc , in particular (emphasis mine): 您可以在流包javadoc中阅读有关懒惰的更多信息,尤其是(强调我的):

Many stream operations, such as filtering, mapping, or duplicate removal, can be implemented lazily, exposing opportunities for optimization. 许多流操作(例如过滤,映射或重复删除)可以延迟实施,从而暴露出进行优化的机会。 For example, "find the first String with three consecutive vowels" need not examine all the input strings. 例如,“使用三个连续的元音查找第一个字符串”不需要检查所有输入字符串。 Stream operations are divided into intermediate (Stream-producing) operations and terminal (value- or side-effect-producing) operations. 流操作分为中间(流产生)操作和终端(产生值或副作用)操作。 Intermediate operations are always lazy. 中间操作总是很懒。


#4楼

Unless your list is really huge (thousands of elements), using streams here is just expensive, and even makes the code harder to understand. 除非您的列表确实很大 (成千上万个元素),否则在此处使用流非常昂贵,甚至会使代码难以理解。

Note: java is NOT a functional language (and jvm isn't particularily suited for implementing functional languages efficiently). 注意:java不是一种功能语言(而jvm并不特别适合有效地实现功能语言)。

Much simpler and more efficiant is (on all Iterable's): (在所有Iterable上)更简单,更有效:

for (MyType walk : lst)if (walk > 5) { do_whatever; break; }

Or if you wanna skip the iterator: 或者,如果您想跳过迭代器:

for (int x=0; x<list.size(); x++)if (list.get(x) > 5 { do_whatever; break; }

Actually, I really wonder why some many people suggest this complex and expensive streams machinery, even for trivial things like getting the first element of an array. 实际上,我真的很奇怪,为什么有人建议使用这种复杂而昂贵的流机制,即使对于诸如获取数组的第一个元素这样的琐碎事情也是如此。 (yes: arrays are still supported in Java8). (是的:Java8仍然支持数组)。


#5楼

return dataSource.getParkingLots().stream().filter(parkingLot -> Objects.equals(parkingLot.getId(), id)).findFirst().orElse(null);

I had to filter out only one object from a list of objects. 我只需要从对象列表中过滤出一个对象。 So i used this, hope it helps. 所以我用了这个,希望对你有帮助。


#6楼

In addition to Alexis C 's answer, If you are working with an array list, in which you are not sure whether the element you are searching for exists, use this. 除了Alexis C的答案外,如果您正在使用数组列表(不确定要搜索的元素是否存在)中,请使用此列表。

Integer a = list.stream().peek(num -> System.out.println("will filter " + num)).filter(x -> x > 5).findFirst().orElse(null);

Then you could simply check whether a is null . 然后,您可以简单地检查a是否为null

通过谓词查找第一个元素相关推荐

  1. python中prime_在AP中查找第一个元素,该元素是Python中给定Prime的倍数

    假设我们有一个AP系列的第一项(A)和共同差(d),并且我们还有素数P,我们必须找到给定AP中第一个元素的位置,该位置是AP的倍数.给定素数P. 因此,如果输入像A = 3,D = 4,P = 5,则 ...

  2. 查找满足断言的第一个元素

    问题:查找满足断言的第一个元素 我刚刚开始使用Java 8的lambdas,我尝试去实现一些我在函数式语言里面经常用的 例如,大部分的函数式语言里有一些查找函数,针对序列或者list进行操作,返回使得 ...

  3. python中用于返回元组中元素最小值的是_• 编写函数,查找序列元素的最大值和最小值。给定一个序列,返回一个元组,其中元组第一个元素为序列最大值,第二个元素为序列最小值 。_学小易找答案...

    [计算题]编写函数 demo(m,n) ,接收两个正整数作为参数,返回一个元组,其中第一个元素为最大公约数,第二个元素为最小公倍数. (4.0分) [计算题]递归算法计算组合数.实现函数 cni(n, ...

  4. python list查找元素_使用python list 查找所有匹配元素的位置实例

    使用python list 查找所有匹配元素的位置实例 如下所示: import re word = "test" s = "test abcdas test 1234 ...

  5. class 第一个元素_第二章(第3节):网页元素定位和操作

    大家仔细思考一下,我们用 selenium 操控浏览器是什么意思,其实就是用 selenium 模拟人上网,也就是说人用浏览器能做的任何事情,我们用 selenium 都可以做,selenium 就如 ...

  6. java查找链表中间元素_如何通过Java单次查找链表的中间元素

    java查找链表中间元素 您如何一次找到LinkedList的中间元素是一个编程问题,在电话采访中经常问Java和非Java程序员. 这个问题类似于检查回文或 计算阶乘 ,有时Interviewer还 ...

  7. css3怎么排除第一个,css怎么排除第一个子元素

    css排除第一个子元素的方法:1.通过使用伪类选择器":not"实现排除:2.通过使用"nth-of-type"或者"nth-child"实 ...

  8. perl 哈希数组的哈希_第一个元素使用哈希在数组中出现K次

    perl 哈希数组的哈希 Prerequisite: Hashing data structure 先决条件: 哈希数据结构 Problem statement: 问题陈述: Find the fir ...

  9. php 查找数组相同元素,查找数组中重复的元素

    本文收集整理关于查找数组中重复的元素的相关议题,使用内容导航快速到达. 内容导航: Q1:在c语言中输入数组两个数组,查找重复元素并输出怎么写啊 可以一次读入N个数据.可以考虑以回车结束读入的一组. ...

最新文章

  1. 原创 | 从席卷全球的“刷脸”乱象,看国内人脸识别立法方向
  2. 打不死我的,终将使我强大!DevOps黑客马拉松参赛心得
  3. 数字图像处理学习路线
  4. 内外网同时运行路由设置
  5. 爬取豆瓣电影top250
  6. 正则表达式(只能操作字符串类型)
  7. oracle百度坐标系火星转换,标准坐标系与火星坐标系(高德)百度坐标系之间互转...
  8. Python爬取拉勾网招聘信息并可视化分析
  9. OSPF-1.ospf基础及工作流程
  10. 均匀点云边界检测——密度查找(1/2)
  11. 神经网络常用术语(Updating)
  12. 原生js代码实现图片放大境效果
  13. pythonapi_Python API
  14. 机器学习概要(MACHINE LEARNING SUMMARY)
  15. 关于单应性矩阵的理解:Homography matrix for dummies
  16. 高效时间管理的18个黄金法则
  17. 石头剪刀布Java实现
  18. PS轻松制作GIF动态图
  19. 龙场悟道,王阳明悟到了什么?
  20. MEM/MBA数学强化(03)整式与分式的运算

热门文章

  1. zabbix如何实现微信报警
  2. jQuery给页面弹出层添加半透明背景
  3. 实现gridview中checkbox的全选和反选,以及固定gridview列字符串的长度,多余的以...表示...
  4. 解决 Chrome 请停用以开发者模式运行的扩展程序
  5. 操作数据----DML语句
  6. Oracle 执行长SQL
  7. Windows Phone 获取联系人
  8. 解决win7检测不到第二个显示器的方法
  9. 在 Ubuntu 中更换字体
  10. Excel 【数据透视表】 -【动态表图】 之核心 -【切片器】