简体   繁体   English

Java8 - 在Map中搜索值

[英]Java8 - Search values in a Map

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) 我正在学习Java8,并希望了解如何将以下内容转换为Java8流API,在找到第一个“匹配”后它会“停止”(如下面的代码所示)

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. 这是在entrySet的Stream中搜索匹配并在找到匹配时返回键的组合,否则返回-1。

What you need is the Stream#findFirst() method once you have filtered the Stream using your predicate. 一旦使用谓词过滤了Stream,您需要的是Stream#findFirst()方法。 Something like this: 像这样的东西:

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

This will return an Optional as there may not be any elements left after the filtering. 这将返回一个Optional,因为过滤后可能没有任何元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM