性能:搜索地图对象



我有一个Map(Integer,String)。有没有一种快速的方法来搜索映射的字符串值?

假设您正在使用Java,并且您的MapHashMap<Integer, String>:

Map<Integer, String> map = new HashMap<>(); //create the map (in this case an HashMap) of the desired type

要在地图中添加一些值,请使用:map.put(desiredIntegerKey, desiredStringValue);

然后,您可以通过以下方式迭代字符串值集合:

for (String value : map.values()) { //loop to iterate over all the string values contained by the map
    //do something with the variable value
    if (value.contains("something")) {
        //this is just an example if you are searching for a string in the map containing a specific sub-string
    }
}

所以基本上,您可以使用字符串值搜索或执行任何您想要的操作。

或者,如果您还需要对密钥的引用,您也可以迭代密钥值的集合:

for (Integer key : map.keySet()) { //loop to iterate over all the integer keys contained by the map
    String value = map.get(key);
    if (value.contains("something")) {
        //in this case you have also the value of the integer key stored in the key variable
    }
}

最新更新