Java8 : stream findFirst result
Well, as for me, the best way is to use functional programing and continue to work with optional. So, for example if you need to pass this string to some service, you can do:
String fisrstString = myList.stream().findFirst().get();
service.doSomething(fisrstString);
But this looks not so good. Instead you can use the pros of functional programing, and do:
myList.stream().findFirst().ifPresent(service::doSomething);
First you will not get a NPE
, but a NoSuchElementException
. Second, it's you who might be sure; but other people might come along and don't realize that it will not throw an exception.
For a sandbox project - yes you would not care and can ignore the warning; for production code I would not disable it (even if you could).
And the last point is that if you are so sure, why not throw an exception?
orElseThrow(IAmSureThisWillNotHappenException::new)
You should make use of the Optional
returned by findFirst()
instead of trying to get its value (if it's actually present).
myList.stream()
.findFirst()
.ifPresent(/* consume the string here, if present */);
The Optional.ifPresent
method receives a Consumer
that will be used only if the Optional
contains a non-null value.
The problem is that we Java developers are so used to the imperative paradigm... In particular, we are used to getting an object and pushing it i.e. to a method:
String myString = "hello"; // getting an object here
System.out.println(myString); // pushing the object to System.out here
// (via the println method)
With the Optional
returned by Stream.findFirst()
you were doing the same as above:
String myString = myList.stream()
.findFirst()
.get(); // getting a string here
System.out.println(myString); // pushing the string here
On the other hand, the functional paradigm (including Optional
) usually works the other way:
myList.stream()
.findFirst()
.ifPresent(myString -> System.out.println(myString));
Here, you don't get the string and then push it to some method. Instead, you provide an argument to Optional
's ifPresent
operation and let the implementation of Optional
push the value to your argument. In other words, you pull the value wrapped by the Optional
by means of ifPresent
's argument. ifPresent
will then use this Consumer
argument, only if the value is present.
This pull pattern is seen a lot in functional programming and is very useful, once you get used to it. It just requires us developers to start thinking (and programming) in a different way.