如果我有一个用Java实现Map接口的对象,并且我希望对其中包含的每一对进行迭代,那么最有效的方法是什么?
元素的顺序是否取决于我对接口的特定映射实现?
如果我有一个用Java实现Map接口的对象,并且我希望对其中包含的每一对进行迭代,那么最有效的方法是什么?
元素的顺序是否取决于我对接口的特定映射实现?
当前回答
public class abcd{
public static void main(String[] args)
{
Map<Integer, String> testMap = new HashMap<Integer, String>();
testMap.put(10, "a");
testMap.put(20, "b");
testMap.put(30, "c");
testMap.put(40, "d");
for (Integer key:testMap.keySet()) {
String value=testMap.get(key);
System.out.println(value);
}
}
}
OR
public class abcd {
public static void main(String[] args)
{
Map<Integer, String> testMap = new HashMap<Integer, String>();
testMap.put(10, "a");
testMap.put(20, "b");
testMap.put(30, "c");
testMap.put(40, "d");
for (Entry<Integer, String> entry : testMap.entrySet()) {
Integer key=entry.getKey();
String value=entry.getValue();
}
}
}
其他回答
这是一个由两部分组成的问题:
如何迭代地图条目-@ScArcher2完美地回答了这个问题。
迭代的顺序是什么?如果您只是使用Map,那么严格来说,没有排序保证。因此,您不应该真正依赖任何实现给出的顺序。然而,SortedMap接口扩展了Map并提供了您所需要的内容——实现将始终提供一致的排序顺序。
NavigableMap是另一个有用的扩展-这是一个SortedMap,它提供了其他方法,用于根据条目在键集中的顺序位置查找条目。因此,这可能会从一开始就消除迭代的需要——在使用higherEntry、lowerEntry、ceilingEntry或floorEntry方法后,您可能能够找到所需的特定条目。descendingMap方法甚至为您提供了一种反转遍历顺序的显式方法。
我相信这是最简单的方法。。。
/* For example, this could be a map object */
Map<String, Integer> MAP = new Map<>();
// Do something like put keys/value pairs into the map, etc...
MAP.put("Denver", 35);
MAP.put("Patriots", 14);
/* Then, simply use a for each loop like this to iterate */
for (Object o : MAP.entrySet()) {
Map.Entry pair = (Map.Entry) o;
// Do whatever with the pair here (i.e. pair.getKey(), or pair.getValue();
}
使用Java 8:
map.entrySet().forEach(entry -> System.out.println(entry.getValue()));
正确的方法是使用公认的答案,因为它是最有效的。我发现下面的代码看起来有点干净。
for (String key: map.keySet()) {
System.out.println(key + "/" + map.get(key));
}
迭代地图非常简单。
for(Object key: map.keySet()){
Object value= map.get(key);
//Do your stuff
}
例如,您有一个Map<String,int>数据;
for(Object key: data.keySet()){
int value= data.get(key);
}