如果我有一个用Java实现Map接口的对象,并且我希望对其中包含的每一对进行迭代,那么最有效的方法是什么?

元素的顺序是否取决于我对接口的特定映射实现?


当前回答

Map<String, String> map = ...
for (Map.Entry<String, String> entry : map.entrySet()) {
    System.out.println(entry.getKey() + "/" + entry.getValue());
}

在Java 10+上:

for (var entry : map.entrySet()) {
    System.out.println(entry.getKey() + "/" + entry.getValue());
}

其他回答

Java 8:

可以使用lambda表达式:

myMap.entrySet().stream().forEach((entry) -> {
    Object currentKey = entry.getKey();
    Object currentValue = entry.getValue();
});

有关详细信息,请遵循以下步骤。

Lambda表达式Java 8

在Java1.8(Java8)中,通过使用Aggregate操作(Stream操作)中的forEach方法,这变得更加容易,它看起来类似于Iterable接口中的迭代器。

只需将下面的粘贴语句复制到代码中,并将HashMap变量从hm重命名为HashMap变量,即可打印出键值对。

HashMap<Integer,Integer> hm = new HashMap<Integer, Integer>();
/*
 *     Logic to put the Key,Value pair in your HashMap hm
 */

// Print the key value pair in one line.

hm.forEach((k, v) -> System.out.println("key: " + k + " value:" + v));

// Just copy and paste above line to your code.

下面是我尝试使用Lambda表达式的示例代码。这东西太酷了。必须尝试。

HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
    Random rand = new Random(47);
    int i = 0;
    while(i < 5) {
        i++;
        int key = rand.nextInt(20);
        int value = rand.nextInt(50);
        System.out.println("Inserting key: " + key + " Value: " + value);
        Integer imap = hm.put(key, value);
        if( imap == null) {
            System.out.println("Inserted");
        } else {
            System.out.println("Replaced with " + imap);
        }               
    }

    hm.forEach((k, v) -> System.out.println("key: " + k + " value:" + v));

Output:

Inserting key: 18 Value: 5
Inserted
Inserting key: 13 Value: 11
Inserted
Inserting key: 1 Value: 29
Inserted
Inserting key: 8 Value: 0
Inserted
Inserting key: 2 Value: 7
Inserted
key: 1 value:29
key: 18 value:5
key: 2 value:7
key: 8 value:0
key: 13 value:11

同样也可以使用Spliterator。

Spliterator sit = hm.entrySet().spliterator();

更新


包括指向Oracle文档的文档链接。有关Lambda的更多信息,请访问此链接,必须阅读聚合操作,对于Spliterator,请访问该链接。

Map上的一个有效迭代解决方案是从Java5到Java7的for循环。这里是:

for (String key : phnMap.keySet()) {
    System.out.println("Key: " + key + " Value: " + phnMap.get(key));
}

在Java8中,可以使用lambda表达式对Map进行迭代。这是一个增强的forEach

phnMap.forEach((k,v) -> System.out.println("Key: " + k + " Value: " + v));

如果要为lambda编写条件,可以这样编写:

phnMap.forEach((k,v)->{
    System.out.println("Key: " + k + " Value: " + v);
    if("abc".equals(k)){
        System.out.println("Hello abc");
    }
});
Map<String, String> map = 
for (Map.Entry<String, String> entry : map.entrySet()) {
    MapKey = entry.getKey() 
    MapValue = entry.getValue();
}

如果我有一个用Java实现Map接口的对象,并且我希望对其中包含的每一对进行迭代,那么最有效的方法是什么?

如果循环键的效率是应用程序的优先事项,那么选择一个Map实现,以您所需的顺序维护键。

元素的顺序是否取决于我对接口的特定映射实现?

是的,绝对。

一些Map实现承诺一定的迭代顺序,而其他的则没有。Map的不同实现维护键值对的不同顺序。

请参见我创建的总结了与Java11捆绑的各种Map实现的表。具体来说,请注意迭代顺序列。单击/轻按以缩放。

您可以看到,有四个Map实现维护一个顺序:

树图并发跳过列表映射链接的哈希映射EnumMap(枚举映射)

NavigableMap界面

其中两个实现NavigableMap接口:TreeMap&ConcurrentSkipListMap。

旧的SortedMap界面被新的NavigableMap界面有效地取代。但您可能会发现第三方实现仅实现旧接口。

自然秩序

如果您想要一个按键的“自然顺序”排列其对的Map,请使用TreeMap或ConcurrentSkipListMap。术语“自然顺序”是指实现Comparable的键类。compareTo方法返回的值用于排序中的比较。

自定义订单

如果要为键指定自定义排序例程以用于维护排序顺序,请传递适合于键类的Comparator实现。使用TreeMap或ConcurrentSkipListMap,传递比较器。

原始插入顺序

如果您希望映射对保持在它们插入映射的原始顺序,请使用LinkedHashMap。

枚举定义顺序

如果使用诸如DayOfWeek或Month之类的枚举作为键,请使用EnumMap类。这个类不仅被高度优化以使用很少的内存并且运行非常快,它还按照枚举定义的顺序维护您的对。例如,对于DayOfWeek,DayOfWeek.MONDAY的键将在迭代时首先找到,DayOfWeek.SUNDAY的密钥将是最后一个。

其他注意事项

在选择Map实现时,还应考虑:

NULLs。某些实现禁止/接受NULL作为键和/或值。并发性。如果要跨线程操作映射,则必须使用支持并发的实现。或者使用Collections::synchronizedMap包装映射(不太可取)。

以上图表中涵盖了这两个考虑因素。