[New Features of Java 8] Java Stream uses findFirst() to find a piece of data that meets the conditions

StreamoffindFirstMethod finds the first element in this stream asOptional

If there are no elements in the stream,findFirstReturn emptyOptional

If the stream has no order, thenfindFirstAny element can be selected.

iffindFirstThe selected elements arenull, it will throwNullPointerException

findFirst declaration in javadoc

Optional<T> findFirst() 

return:findFirst method returnsOptionalThe element containing the first element in the stream.
abnormal: If a null value is selected, findFirst will throw NullPointerException.

findFirst is a short-circuit terminal operation (short-circuiting terminal operation), a stream operation is a set of intermediate operations and terminal operations, if an intermediate operation can generate a finite stream for infinite input, it is a short circuit (short-circuiting)。

Let’s look at a set of examples below

Example 1: Suppose we have a stream of integers and callfindFirstmethod.

Stream.of(50, 60, 70).findFirst()
    .ifPresent(s -> System.out.println(s)); 

The output is 50, which is the first element of the stream.



package com.concretepage;
import java.util.Arrays;
import java.util.List;
public class FindFirstDemo1 {
  public static void main(String[] args) {
	List<String> list = Arrays.asList("Vijay", "Suresh", "Vinod");
	String output = list.stream()
	  .filter(e -> e.startsWith("V")) // Vijay, Vinod
	  .findFirst() //Vijay

	List<Integer> numList = Arrays.asList(31, 32, 33, 34);
	  .filter(n -> n % 2 == 0) // 32, 34
	  .findFirst() //32
	  .ifPresent(e -> System.out.println(e));



Example 2:The following is usedIntStreamLongStreamandDoubleStreamoffindFirstExample of method.


package com.concretepage;
import java.util.stream.DoubleStream;
import java.util.stream.IntStream;
import java.util.stream.LongStream;
public class FindFirstDemo2 {
  public static void main(String[] args) {
	IntStream intStream = IntStream.of(10, 20, 30, 40);
	intStream.filter(i -> i > 20).findFirst()
	     .ifPresent(i -> System.out.println(i));

	LongStream longStream = LongStream.of(100, 200, 300);
	longStream.filter(l -> l < 250).findFirst()
	     .ifPresent(l -> System.out.println(l));

	DoubleStream doubleStream = DoubleStream.of(100.52, 200.55, 300.66);
	doubleStream.filter(d -> d > 200).findFirst()
	     .ifPresent(l -> System.out.println(l));



Example 3: Below is an example of findFirst with parallel streams.


package com.concretepage;
import java.util.ArrayList;
import java.util.List;
public class FindFirstDemo3 {
  public static void main(String[] args) {
	List<Employee> list = new ArrayList<>();
	list.add(new Employee("Emp A", 3000));
	list.add(new Employee("Emp B", 4000));
	list.add(new Employee("Emp C", 5000));
	list.add(new Employee("Emp D", 6000));

	    .filter(e -> e.getSal() >= 4000 && e.getSal() <= 5000)
	    .mapToInt(e -> e.getSal())
		.ifPresent(s -> System.out.println(s));
class Employee {
  private String name;
  private int sal;

  public Employee(String name, int sal) {
	this.name = name;
	this.sal = sal;
  //Sets and Gets



Example 4: Below is an example of findFirst with null values.


package com.concretepage;
import java.util.stream.Stream;
public class FindFirstDemo4 {
  public static void main(String[] args) {
	Stream.of(null, "A").
	    findFirst().ifPresent(s -> System.out.println(s));

The output will be NullPointerException.


【1】Java doc: Stream
【2】Java Stream findFirst()

Related Posts

Detailed explanation of IDEA debugging skills

Springboot/Springcloud integrates ELK platform, (Filebeat method) log collection and management (Elasticsearch+Logstash+Filebeat+Kibana)

In-depth understanding of Hbase (2) Detailed explanation of RegionServer in Hbase

Spring source code analysis

LeetCode 45. Jumping Game ② (Super detailed)

Integrate SSM framework

Implementing the check-in function of an app is not as complicated as you think~

[Java SE]String class

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>