Close

Java 8 Streams - IntStream.findFirst Examples

Java 8 Streams Java Java API 


Interface:

java.util.stream.IntStream

java.lang.AutoCloseableAutoCloseablejava.util.stream.BaseStreamBaseStreamjava.util.stream.IntStreamIntStreamLogicBig

Method:

OptionalInt findFirst()

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


Examples


package com.logicbig.example.intstream;

import java.util.stream.IntStream;

public class FindFirstExample {


public static void main(String... args) {
IntStream intStream = IntStream.of(1, 2, 3, 2, 5, 4);
int i = intStream.findFirst()
.orElse(-1);
System.out.println(i);

//parallel
IntStream intStream2 = IntStream.of(1, 2, 3, 2, 5, 4);
int i2 = intStream2.parallel()
.findFirst()
.orElse(-1);
System.out.println(i2);
}
}

Output

1
1




For unordered stream (having no encounter order), the result is still the same, that's because unordered() method does not actually unordered or shuffle the elements but it just removes the ordered characteristics from the stream which improves the performance in case of parallel processing.

package com.logicbig.example.intstream;

import java.util.stream.IntStream;

public class FindFirstExample2 {

public static void main(String... args) {
IntStream intStream = IntStream.of(1, 2, 3, 2, 5, 4);
int i = intStream.unordered()
.findFirst()
.orElse(-1);
System.out.println(i);

//parallel
IntStream intStream2 = IntStream.of(1, 2, 3, 2, 5, 4);
int i2 = intStream2.unordered()
.parallel()
.findFirst()
.orElse(-1);
System.out.println(i2);

}
}

Output

1
1




See Also