Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java8 - Search values in a Map

Tags:

java

java-8

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;
}
like image 813
Dave Avatar asked Dec 15 '22 04:12

Dave


1 Answers

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.

like image 70
Eran Avatar answered Dec 17 '22 00:12

Eran