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. index页面数据展示为设定的命名

    数据库表里面字段的值想用另一种命名形式展示,如1是 是,2是 否  解决方法: 用到formatter ,{field: 'params', title: '参数', width: 100, sort ...

  2. .net+easyui系列--验证框

    1.允许从 0 到 10个字符 <input id="vv" class="easyui-validatebox" data-options=" ...

  3. 【转】[转]order by 1是什么意思?

    [转][转]order by 1是什么意思? ORDER BY 1 表示 所select 的字段按第一个字段排序 ORDER BY ASC应该没有这样写法,ORDER BY 后面不是字段就是数字, 可 ...

  4. Unity5.0 手动激活

    提供Unity5.0.1.f1(32-bit)下载http://pan.baidu.com/s/1bg5sDK 密码 ns75 有时候会发现,用激活工具是激活不了的,这个时候就要手动激活,其实个人觉得 ...

  5. 学习java随笔第四篇:运算符

    算术运算符 "+":加法运算符,也可做字符连接用途 "-":减法运算符 "*":乘法运算符 "/":除法运算符 &quo ...

  6. AbstractMethodError using UriBuilder on JAX-RS

    问题描述:Eclipse调试JAX-RS服务没问题,但是在发布服务端时候抛出异常 java.lang.AbstractMethodError: javax.ws.rs.core.UriBuilder. ...

  7. JDBC连接池以及动态SQL处理

    复习一下: 1.先创建一个properties配置文件 ClasssName=oracle.jdbc.driver.OracleDriver url=jdbc:oracle:thin:@服务器IP:端 ...

  8. web应用程序servlet的映射名称的规则及请求过程

    首先用MyEclipse创建一个web Project(工程名起为TestServletProject),新建一个Servlet(这里servlet的名字起TestServlet),将请求的servl ...

  9. DOM 操作内容 innerText/innerHTML

    DOM 操作内容 innerText/innerHTML innerText属性(firefox不支持,可用 textContent)var div = document.getElementById ...

  10. 修改Tomcat命令窗口的名字

    在运行多个tomcat窗口的时候,可以通过修改tomcat命令窗口的名字来区分不同的tomcat,修改如下: 找到tomcat下面的这个文件:tomcat_home\bin\catalina.bat, ...