Close

Java 8 Streams - Stream.findFirst Examples

Java 8 Streams Java Java API 


Interface:

java.util.stream.Stream

java.lang.AutoCloseableAutoCloseablejava.util.stream.BaseStreamBaseStreamjava.util.stream.StreamStreamLogicBig

Method:

Optional<T> findFirst()

Returns an Optional describing the first element of this stream, or an empty Optional if the stream is empty. If the stream has no encounter order, then any element may be returned. This is a terminal-short-circuiting operation


Examples


package com.logicbig.example.stream;

import java.util.Optional;
import java.util.stream.Stream;

public class FindFirstExample {

public static void main(String... args) {
Stream<Object> s = Stream.empty();
Optional<Object> opt = s.findFirst();
System.out.println(opt.isPresent());
}
}

Output

false




package com.logicbig.example.stream;

import java.util.Optional;
import java.util.stream.Stream;

public class FindFirstExample2 {

public static void main(String... args) {
Stream<String> s = Stream.of("one", "two", "three", "four");
Optional<String> opt = s.findFirst();
if (opt.isPresent()) {
System.out.println(opt.get());
}
}
}

Output

one




Parallel stream example

package com.logicbig.example.stream;

import java.util.Optional;
import java.util.stream.Stream;

public class FindFirstExample3 {

public static void main(String... args) {
Stream<String> s = Stream.of("one", "two", "three", "four");
Optional<String> opt = s.parallel()
.findFirst();
if (opt.isPresent()) {
System.out.println(opt.get());
}
}
}

Output

one




    private Page resolvePage(HttpServletRequest req) {
String path = req.getRequestURI()
.substring(req.getContextPath()
.length());
Object obj = req.getServletContext()
.getAttribute("pages");

if (obj instanceof List) {
Optional<Page> first = ((List<Page>) obj).stream()
.filter(p -> path.equals(p.getPath()))
.findFirst();

if (first.isPresent()) {
return first.get();
}
}
return null;
}
Original Post
    @Override
public Customer load(long id) {
Optional<Customer> first = customers.stream()
.filter(c -> c.getCustomerId() == id)
.findFirst();
return first.isPresent() ? first.get() : null;
}




This example finds the first int which is multiple of 3.

package com.logicbig.example;

import java.util.OptionalInt;
import java.util.stream.IntStream;

public class FindFirstExample {

public static void main (String[] args) {
IntStream stream = IntStream.of(1, 2, 3, 4, 5, 6);
stream = stream.filter(i -> i % 3 == 0);
OptionalInt opt = stream.findFirst();
if (opt.isPresent()) {
System.out.println(opt.getAsInt());
}
}
}

Output

3
Original Post




See Also