Java8 - Find Values ​​on a Map

I am learning Java8 and see how you can convert the following to the Java8 streaming API, where it “stops” after searching for the first “hit” (as 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;
}
+4
source share
2 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 finding a match in the stream entrySetand returning either the key if a match is found, or -1.

+11
source

You need the Stream # findFirst () method once you have filtered the Stream using your predicate. Something like that:

map.entrySet()
    .stream()
    .filter(e -> e.getValue().equalsIgnoreCase(searchTerm))
    .findFirst();

Optional, .

+1

Source: https://habr.com/ru/post/1649258/


All Articles