Stream findFirst() Method in JavaThe 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 ExceptionAs 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 "
Next TopicBalanced Parentheses in Java
|