Wednesday, March 30, 2016

How to find the first element of Stream in Java 8 - findFirst() Example

In Java 8, you can use the Stream.findFirst() method to get the first element of Stream in Java. This is a terminal operation and often used after applying several intermediate operations e.g. filtermappingflattening etc. For example, if you have a List of String and you want to find the first String whose length is greater than 10, you can use the findFirst() method along withstream() and filter() to get that String. The stream() method gets the Stream from a List, which then allow you to apply several useful methods defined in the java.util.Stream class e.g. filter()map()flatMap() etc.

One of the important thing to know while using for writing such logic is that all intermediate operations e.g. filter()map() etc arelazy and they are only executed when a terminal operation like findFirst() or forEach() is called.

for (String gadget : gadgets) {
  if (gadget.length() > 10) {
    System.out.println("Prior ot Java 8: " + gadget);
    break;
  }
}

In Java 8, you can achieve the same effect by using the findFirst() method of java.util.stream.Stream class as shown below:

String item = gadgets.stream()
    .filter(s -> s.length() > 10)
    .findFirst()
    .orElse("");

java-8-streams-map-examples

package com.mkyong.java8; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Arrays; import java.util.List; im...