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 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?

asked May 16 at 13:28
siki

509313

   
It's not inefficient, Java 8 Stream implementation is lazy evaluated, so filter is applied only to terminal operation. Same question here:stackoverflow.com/questions/21219667/stream-and-lazy-evaluation –  Marek GregorMay 16 at 13:35 
   
Cool. That's what I hoped it'd do. It would've been a major design flop otherwise. –  sikiMay 16 at 13:52

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:

List<Integer> list = new ArrayList<>(Arrays.asList(1,10,3,7,5));
int a = list.stream().filter(x -> {System.out.println("filtered"); return x > 5;}).findFirst().get();
System.out.println(a);

Which outputs:

filtered
filtered
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.

answered May 16 at 13:37
ZouZou

24.3k52752

3  
list.stream().peek(System.out::println).filter(x -> x>5).findFirst()will demonstrate it as well… –  Holger May 19 at 8:42

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

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.

lambda -- Java 8 find first element by predicate的更多相关文章

  1. Lambda&Java多核编程-5-函数式接口与function包

    从前面的总结中我们知道Lambda的使用场景是实现一个函数式接口,那么本篇就将阐述一下何为函数式接口以及Java的function包中提供的几种函数原型. 函数式接口 早期也叫作SAM(Single ...

  2. Lambda&Java多核编程-6-方法与构造器引用

    在Lambda&Java多核编程-2-并行与组合行为一文中,我们对Stream<Contact>里的每一位联系人调用call()方法,并根据能否打通的返回结果过滤掉已经失效的项. ...

  3. Eclipse启动Tomcat时发生java.lang.IllegalArgumentException: <session-config> element is limited to 1 occurrence

    在学习struts 2时,为了方便,直接从下载的struts的apps目录下的struts2-blank.war压缩包下的WEB-INF\复制的web.xml,当我启动Tomcat时,发生 java. ...

  4. java集合(3)-Java8新增的Predicate操作集合

    Java8起为Collection集合新增了一个removeIf(Predicate filter)方法,该方法将批量删除符合filter条件的所有元素.该方法需要一个Predicate(谓词)对象作 ...

  5. Lambda&Java多核编程-7-类型检查

    本篇主要介绍Lambda的类型检查机制以及周边的一些知识. 类型检查 在前面的实践中,我们发现表达式的类型能够被上下文所推断.即使同一个表达式,在不同的语境下也能够被推断成不同类型. 这几天在码一个安 ...

  6. java selenium后报错Element not found in the cache元素定位要重新赋值之前的定义

    习惯上把定位的元素在操作之前就定位好, 例如: WebElement element1=driver.findElement(...);      ----------declaration1 Web ...

  7. Java [Leetcode 169]Majority Element

    题目描述: Given an array of size n, find the majority element. The majority element is the element that ...

  8. [Java 8 Lambda] java.util.stream 简单介绍

    包结构例如以下所看到的: 这个包的结构非常easy,类型也不多. BaseStream接口 全部Stream接口类型的父接口,它继承自AutoClosable接口,定义了一些全部Stream都具备的行 ...

  9. Java [leetcode 27]Remove Element

    题目描述: Given an array and a value, remove all instances of that value in place and return the new len ...

随机推荐

  1. SQL Server 游标

    结果集,结果集就是select查询之后返回的所有行数据的集合. 在关系数据库中,我们对于查询的思考是面向集合的.而游标打破了这一规则,游标使得我们思考方式变为逐行进行. 正常面向集合的思维方式是: 而 ...

  2. Python实战:美女图片下载器,海量图片任你下载

    Python应用现在如火如荼,应用范围很广.因其效率高开发迅速的优势,快速进入编程语言排行榜前几名.本系列文章致力于可以全面系统的介绍Python语言开发知识和相关知识总结.希望大家能够快速入门并学习 ...

  3. php快速排序

    快速排序是排序中常用的,效率据说还不错,它使用分治算法实现 将一个大的需要排序的序列,分成两个较小的序列!怎么分呢,需要从序列中找出一个元素作为参考元素,通常的做法是拿第一个元素作为参考元素.当一个序 ...

  4. javascript技巧字典【转藏】

    2015-12-31 js判断undefined类型 if (reValue== undefined){    alert("undefined");    }  发现判断不出来, ...

  5. Error parsing XML: not well-formed (invalid token)

    从网络上或别的文件复制粘贴进来的代码有隐含格式,可将内容先粘贴进记事本清除格式,再复制粘贴进工程文件,即可解决此问题 注:1. 要使工程文件全选清空, 2. 若粘贴后刷新仍无效果,可手动输入

  6. TCP服务器端和客服端(一)

    就是一个客服端(Socket)和服务器(ServerSocket)端的链接间.我的理解是一个服务端可以链接多个客服端. 在客服端有输入流outPutStream. 用于发送数据 在服务器端有输出流.i ...

  7. ios7 苹果原生二维码扫描(和微信类似)

    在ios7苹果推出了二维码扫描,以前想要做二维码扫描,只能通过第三方ZBar与ZXing. ZBar在扫描的灵敏度上,和内存的使用上相对于ZXing上都是较优的,但是对于 “圆角二维码” 的扫描确很困 ...

  8. CSS 创建

    当读到一个样式表时,浏览器会根据它来格式化 HTML 文档. 如何插入样式表 插入样式表的方法有三种: 外部样式表 内部样式表 内联样式 外部样式表 当样式需要应用于很多页面时,外部样式表将是理想的选 ...

  9. Python:列表

    #!/usr/bin/python3 #列表 是可变的,可修改的 listDemo = ["one","two","three"," ...

  10. java_泛型(2016-11-17)

    没有自己敲,这篇博客讲的不错,直接记录. 犯懒啊 重点关注 T,?以及擦除 Java总结篇系列:Java泛型:http://www.cnblogs.com/lwbqqyumidi/p/3837629. ...