Skip to content
Advertisement

Java stream find value by key if exists

I’m having simple DataStructure

JavaScript

And I need to return value from `List’ based on key and I want to do it Java8 way, with streams. I think code speaks for himself:

JavaScript

How can I modify findValueStream() to not throw NoSuchValueException while I search for non existing key? I don’t want to return Optional<String> because this method is already used in a lot of places in project. And, ofcourse I’v tried map, ifPresent, anyMatch, just can’t find the right way to do it.

Advertisement

Answer

You shall use Stream.findFirst with an Optional.orElse like :

JavaScript

Note: The above uses the Stream.map to map the stream of DataStructure to a corresponding stream of value.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement