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. Spring声明式事务(xml配置事务方式)

    Spring声明式事务(xml配置事务方式) >>>>>>>>>>>>>>>>>>>& ...

  2. 今天把PHP复习了一下.

    记录一下今天复习内容. $_GET[''] $_POST $_SESSION $_COOKIE 常用的 $var='a'; global 全局变量$GLOBALS[''] $$var (动态变量名的变 ...

  3. wcf入门教程

    一.概述 Windows Communication Foundation(WCF)是由微软发展的一组数据通信的应用程序开发接口,可以翻译为Windows通讯接口,它是.NET框架的一部分.由 .NE ...

  4. HTTP状态吗汇录

    页面Http状态查询工具说明 建议直接Ctrl+F来查找状态码 如果向您的服务器发出了某项请求要求显示您网站上的某个网页,那么,您的服务器会返回 HTTP 状态代码以响应该请求. 如果向您的服务器发出 ...

  5. 虚拟化技术与"云"

    虚拟化技术: 如网站在某一时间访问量大,平时访问量少,如果一直保持大量的服务器提供服务,显示效率好低,浪费资源,在 不增减服务器,存储设备,网络等实际物理设备,而是利用软件将这些物理设备虚拟化,在有必 ...

  6. 配置处理结果result

    Action处理完用户请求后返回一个字符串,整个字符串就是一个逻辑视图名. 除此之外,struts2还支持多种结果映射,struts2将结果转为实际资源时,不仅可以是JSP视图资源,也可以是FreeM ...

  7. jQuery的延迟对象

    之前看别人的demo,发现在延迟对象被resolve时要执行的代码,有时会写在deferred.then方法里执行,有时会写在deferred.done方法里执行. 这让对延迟对象一知半解的我非常困惑 ...

  8. [Linux]命令行模式切换

    图形界面进入命令:Ctrl+Alt+T 进入终端命令:Ctrl+Alt+F1 or Ctrl+Alt+F2 切换至图形界面:按Alt+F7

  9. 安装python-MySQLdb 出现error: command 'gcc' failed with exit status 1的解决方法

    >>> yum install MySQL-p* >>>yum install python-devel >>>cd MySQL-python-1 ...

  10. 批处理协同blat自动发邮件

    Blat - A Windows (32 & 64 bit) command line SMTP mailer. Use it to automatically eMail logs, the ...