性能:通过Map Object搜索

时间:2014-04-23 09:23:14

标签: performance map hashset

我有一张地图(整数,字符串)。有没有快速的方法来搜索地图的字符串值?

1 个答案:

答案 0 :(得分:0)

假设您使用的是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
    }
}

所以基本上你可以用字符串值搜索或做任何你想做的事。

或者你也可以迭代key值的集合,如果你还需要引用键:

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
    }
}