I want to know if there is a way to get rid of the warning at findFirst().get()
without using .orElse()
when I know 100% that every time there is a result, so I never get a NoSuchElementException
.
For example let's see the following code:
List<String> myList = new ArrayList<>(); myList.add("Test"); myList.add("Example"); myList.add("Sth"); String fisrstString = myList.stream().findFirst().get(); // here I surely get "Test"
I don't know how other IDEs treat this, but IntelliJ treats that as a warning
'Optional.get()' without 'isPresent()'
I think probably it doesn't know when can you get NoSuchElementException
there and when not, or I have no idea why. I know there are ways to solve this warning(isPresent()
check, .orElse(something)
) but with useless code, so simply I don't want to use those solutions because they are so unnecessary.
Do you have any idea what can I do, or explain how is that treated by the IDE?
The findFirst() method finds the first element in a Stream. So, we use this method when we specifically want the first element from a sequence. When there is no encounter order, it returns any element from the Stream.
Stream findFirst() in Java with examples Stream findFirst() returns an Optional (a container object which may or may not contain a non-null value) 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.
Stream findFirst() vs findAny() – ConclusionUse findAny() to get any element from any parallel stream in faster time.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With