I'm learning Java8 and looking to see how you could convert the following into Java8 streaming API where it 'stops' after finding the first 'hit' (like in the code below)
public int findId(String searchTerm) {
for (Integer id : map.keySet()) {
if (map.get(id).searchTerm.equalsIgnoreCase(searchTerm))
return id;
}
return -1;
}
Without testing, something like this should work :
return map.entrySet()
.stream()
.filter(e-> e.getValue().searchTerm.equalsIgnoreCase(searchTerm))
.findFirst() // process the Stream until the first match is found
.map(Map.Entry::getKey) // return the key of the matching entry if found
.orElse(-1); // return -1 if no match was found
This is a combination of searching for a match in the Stream of the entrySet
and returning either the key if a match is found or -1 otherwise.
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