Java8 - 在Map中搜索值

Dav*_*ave 4 java java-8

我正在学习Java8,并希望了解如何将以下内容转换为Java8流API,在找到第一个'命中'后它会"停止"(如下面的代码所示)

public int findId(String searchTerm) {

    for (Integer id : map.keySet()) {
        if (map.get(id).searchTerm.equalsIgnoreCase(searchTerm))
            return id;
    }
    return -1;
}
Run Code Online (Sandbox Code Playgroud)

Era*_*ran 11

没有测试,这样的东西应该工作:

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
Run Code Online (Sandbox Code Playgroud)

这是在Stream的流中搜索匹配的组合,entrySet如果找到匹配则返回键,否则返回-1.