105
Stream findFirst() Method in Java
The Stream findFirst() method returns an Optional describing the 1st element of the stream, or an Optional, which has to be empty if the stream is empty.
Syntax:
Here, Optional is the container object that can or cannot fetch a non-null value. T is the type of object.
Exception: If a null element is chosen, then the NullPointerException is thrown.
Example 1:
Observe the following program.
FileName: FindFirstExample.java
Output:
11 12
Example 2:
Let’s see another exmaple of the method findFirst().
FileName: FindFirstExample1.java
Output:
Linked List
Example 3: Null Exception
As discussed earlier, a NullPointerException is thrown when a null element is chosen. The following program shows the same.
FileName: FindFirstExample2.java
Output:
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.equalsIgnoreCase(String)" because "" is null at findFirstExample2.lambda$main$0(findFirstExample2.java:15) at java.base/java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:178) at java.base/java.util.Spliterators$ArraySpliterator.tryAdvance(Spliterators.java:1002) at java.base/java.util.stream.ReferencePipeline.forEachWithCancel(ReferencePipeline.java:129) at java.base/java.util.stream.AbstractPipeline.copyIntoWithCancel(AbstractPipeline.java:527) at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:513) at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:499) at java.base/java.util.stream.FindOps$FindOp.evaluateSequential(FindOps.java:150) at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) at java.base/java.util.stream.ReferencePipeline.findFirst(ReferencePipeline.java:647) at findFirstExample2.main(findFirstExample2.java:15)
Next TopicBalanced Parentheses in Java