java8streamfindfirst,Java 8 Stream findFirst() and findAny()

In Java 8 Stream, the findFirst() returns the first element from a Stream, while findAny() returns any element from a Stream.

1. findFirst()

1.1 Find the first element from a Stream of Integers.

Java8FindFirstExample1.java

package com.mkyong.java8;

import java.util.Arrays;

import java.util.List;

import java.util.Optional;

public class Java8FindFirstExample1 {

public static void main(String[] args) {

List list = Arrays.asList(1, 2, 3, 2, 1);

Optional first = list.stream().findFirst();

if (first.isPresent()) {

Integer result = first.get();

System.out.println(result); // 1

} else {

System.out.println("no value?");

}

Optional first2 = list

.stream()

.filter(x -> x > 1).findFirst();

if (first2.isPresent()) {

System.out.println(first2.get()); // 2

} else {

System.out.println("no value?");

}

}

}

Output

1

2

1.2 Find the first element from a Stream of String which is not equal to "node".

Java8FindFirstExample2.java

package com.mkyong.java8;

import java.util.Arrays;

import java.util.List;

import java.util.Optional;

public class Java8FindFirstExample2 {

public static void main(String[] args) {

List list = Arrays.asList("node", "java", "python", "ruby");

Optional result = list.stream()

.filter(x -> !x.equalsIgnoreCase("node"))

.findFirst();

if (result.isPresent()) {

System.out.println(result.get()); // java

} else {

System.out.println("no value?");

}

}

}

Output

java

2. findAny()

2.1 Find any element from a Stream of Integers. If we run the below program, most of the time, the result is 2, it looks like findAny() always returns the first element? But, there is no guaranteed for this, findAny() may return any element from a Stream.

Java8FindAnyExample1.java

package com.mkyong.java8;

import java.util.Arrays;

import java.util.List;

import java.util.Optional;

public class Java8FindAnyExample1 {

public static void main(String[] args) {

List list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

Optional any = list.stream().filter(x -> x > 1).findAny();

if (any.isPresent()) {

Integer result = any.get();

System.out.println(result);

}

}

}

Output

2 // no guaranteed

References

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值