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. ADO.Net技术

    Connection对象 1.连接数据库 通过SqlConnection对象的State属性判断数据库的连接状态: public override ConnectionState State{ get ...

  2. Python教程:操作数据库,MySql的安装详解

    各位志同道合的同仁请点击上方关注 本教程是基于Python语言的深入学习.本次主要介绍MySql数据库软件的安装.不限制语言语法,对MySql数据库安装有疑惑的各位同仁都可以查看一下. 如想查看学习P ...

  3. 两种隐藏元素方式【display: none】和【visibility: hidden】的区别及由此引出的问题

    此前看到一随笔(@任天缘 原文)讲了这个问题,并总结了: [display: none]:隐藏元素及元素内的所有内容,并且该元素的位置.宽高等其他属性值一并“消失”: [visibility: hid ...

  4. KinSlideshow参数设置说明

    [引用来自:http://blog.sina.com.cn/s/blog_4f4f4a5901014zn1.html] Jquery.KinSlideshow参数设置说明: 附:所有参数列表   in ...

  5. “jni.h”: No such file or directory

    VS2010解决方案: 进入 “包含目录“ 方式: 右键项目属性页-> 配置属性->VC++目录->包含目录 在”包含目录“中编辑 添加以下路径: C:\Program Files\ ...

  6. sql server抓取表结构的语句

    sql server 2008抓取方法: ---------------------------------------   SELECT      表名 = Case When A.colorder ...

  7. 3 委托、匿名函数、lambda表达式

    委托.匿名函数.lambda表达式 在 2.0 之前的 C# 版本中,声明委托的唯一方法是使用命名方法.C# 2.0 引入了匿名方法,而在 C# 3.0 及更高版本中,Lambda 表达式取代了匿名方 ...

  8. .NET中的委托——摘自MSDN

    封装一个方法,该方法只有一个参数并且不返回值. 命名空间:  System程序集:  mscorlib(在 mscorlib.dll 中) 语法   C#   public delegate void ...

  9. Set集合中的HashSet集合

    HashSet集合的特点:元素是具备唯一性的,每次存储都要先算出哈希值,看有没相同,没有相同的存储到相应的位置,如果相同则再判断存储进来的值是否与被比较的相同,如果相同,则不再存储,不同就存储 pac ...

  10. windows phone 之ListBox模板选择

    有时做项目时,会遇到一种情况:需要把获取到的数据集合显示到首页,比如新闻,但是: 新闻也分类别啊,比如:图片类新闻.文字类新闻.视频类新闻. 那我们可能采用的模板就不一样了,那么,如何根据类别来选择模 ...