Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map and FindFirst

Is it valid to use findFirst() and map() in pipeline.findFirst is shortcircuit method whereas map is intermediate operation.

this.list.stream().filter(t -> t.name.equals("pavan")).findFirst().map(toUpperCase()).orElse(null);

Is it valid to use map in pipeline like above??

like image 835
pavan Avatar asked Dec 06 '22 17:12

pavan


1 Answers

Yes, you can use map after findFirst. The Key thing to know here is that findFirst() returns an Optional and hence, you can't simply use the return value without first checking whether the optional has got a value or not. The snippet below assumes that you were working with a list of objects of Person class.

Optional<String> result = this.list.stream()
    .filter(t -> t.name.equals("pavan")) // Returns a stream consisting of the elements of this stream that match the given predicate.
    .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.
    .map(p -> p.name.toUpperCase()); // If a value is present, apply the provided mapping function to it, and if the result is non-null, return an Optional describing the result. Otherwise return an empty Optional.

// This check is required!
if (result.isPresent()) {
    String name = result.get(); // If a value is present in this Optional, returns the value, otherwise throws NoSuchElementException.
    System.out.println(name);
} else {
    System.out.println("pavan not found!");
}

One more error with your snippet was where you were using toUpperCase. It needs a String, whereas the implicit argument that was getting passed in your snippet was an object of Person class.

like image 126
Ranjan Avatar answered Dec 09 '22 13:12

Ranjan