When using the new Java8 streams api to find one specific element in a collection, I write code like this:
String theFirstString = myCollection.stream()
.findFirst()
.get();
Here IntelliJ warns that get() is called without checking isPresent() first.
However, this code:
String theFirstString = myCollection.iterator().next();
...yields no warning.
Is there some profound difference between the two techniques, that makes the streaming approach more "dangerous" in some way, that it is crucial to never call get() without calling isPresent() first? Googling around, I find articles talking about how programmers are careless with Optional<> and assume they can call get() whenever.
Thing is, I like to get an exception thrown at me as close as possible to the place to where my code is buggy, which in this case would be where I am calling get() when there is no element to be found. I don't want to have to write useless essays like:
Optional<String> firstStream = myCollection.stream()
.findFirst();
if (!firstStream.isPresent()) {
throw new IllegalStateException("There is no first string even though I totally expected there to be! <sarcasm>This exception is much more useful than NoSuchElementException</sarcasm>");
}
String theFirstString = firstStream.get();
...unless there is some danger in provoking exceptions from get() that I am unaware of?
After reading the response from Karl Bielefeldt and a comment from Hulk, I realized my exception code above was a bit clumsy, here's something better:
String errorString = "There is no first string even though I totally expected there to be! <sarcasm>This exception is much more useful than NoSuchElementException</sarcasm>";
String firstString = myCollection.stream()
.findFirst()
.orElseThrow(() -> new IllegalStateException(errorString));
This looks more useful and will probably come natural in many places. I still feel like I will want to be able to pick one element from a list without having to deal with all of this, but that could just be that I need to get used to these kinds of constructs.