Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java8 : stream findFirst result

Tags:

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?

like image 887
Sunflame Avatar asked Jun 09 '17 13:06

Sunflame


People also ask

What does findFirst () do in Java Stream?

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.

How do I use findFirst in streams?

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.

Which is faster findAny or findFirst?

Stream findFirst() vs findAny() – ConclusionUse findAny() to get any element from any parallel stream in faster time.


1 Answers

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); 
like image 154
Sergii Bishyr Avatar answered Oct 03 '22 11:10

Sergii Bishyr