Iterate over a Map in Java – 在Java中对一个地图进行迭代

最后修改: 2017年 6月 23日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this quick tutorial, we’ll look at the different ways of iterating through the entries of a Map in Java.

在这个快速教程中,我们将了解在Java中迭代Map条目的不同方法。

Simply put, we can extract the contents of a Map using entrySet(), keySet(), or values(). Since these are all sets, similar iteration principles apply to all of them.

简单地说,我们可以使用entrySet()keySet() values()来提取Map的内容。由于这些都是集合,类似的迭代原则适用于所有这些集合。

Let’s have a closer look at a few of these.

让我们仔细看看其中的几个例子。

2. Short Introduction to Map‘s entrySet(), keySet(), and values() Methods

2.简要介绍MapentrySet(), keySet(), 和values()方法

Before we iterate through a map using the three methods, let’s understand what these methods do:

在我们使用这三种方法遍历地图之前,让我们了解一下这些方法的作用。

  • entrySet() – returns a collection-view of the map, whose elements are from the Map.Entry class. The entry.getKey() method returns the key, and entry.getValue() returns the corresponding value
  • keySet() – returns all keys contained in this map as a Set
  • values() – returns all values contained in this map as a Set
Next, let’s see these methods in action.

3. Using a for Loop

3.使用for循环

3.1. Using entrySet()

3.1.使用entrySet()

First, let’s see how to iterate through a Map using the EntrySet:

首先,让我们看看如何使用EntrySetMap中迭代。

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

Here, we’re extracting the Set of entries from our Map and then iterating through them using the classical for-each approach.

在这里,我们从Map中提取条目的Set,然后使用经典的for-each方法对它们进行迭代。

3.2. Using keySet()

3.2.使用keySet()

Alternatively, we can first get all keys in our Map using the keySet method and then iterate through the map by each key:

另外,我们可以首先使用keySet方法获得Map中的所有键,然后按每个键遍历地图。

public void iterateUsingKeySetAndForeach(Map<String, Integer> map) {
    for (String key : map.keySet()) {
        System.out.println(key + ":" + map.get(key));
    }
}

3.3. Iterating Over Values Using values()

3.3.使用values()在数值上进行迭代

Sometimes, we’re only interested in the values in a map, no matter which keys are associated with them. In this case, values() is our best choice:

有时,我们只对map中的值感兴趣,不管哪些键与之相关联。在这种情况下,values()是我们最好的选择。

public void iterateValues(Map<String, Integer> map) {
    for (Integer value : map.values()) {
        System.out.println(value);
    }
}

4. Iterator

4.迭代器

Another approach to perform the iteration is using an Iterator. Next, let’s see how the methods work with an Iterator object.

另一种执行迭代的方法是使用Iterator。接下来,让我们看看这些方法如何与Iterator对象一起工作。

4.1. Iterator and entrySet()

4.1.IteratorentrySet()

First, let’s iterate over the map using an Iterator and entrySet():

首先,让我们用一个迭代器和entrySet()来迭代地图。

public void iterateUsingIteratorAndEntry(Map<String, Integer> map) {
    Iterator<Map.Entry<String, Integer>> iterator = map.entrySet().iterator();
    while (iterator.hasNext()) {
        Map.Entry<String, Integer> entry = iterator.next();
        System.out.println(entry.getKey() + ":" + entry.getValue());
    }
}

Notice how we can get the Iterator instance using the iterator() API of the Set returned by entrySet(). Then, as usual, we loop through the Iterator with iterator.next().

请注意我们如何使用entrySet()返回的iterator() API获得Iterator实例。然后,像往常一样,我们用iterator.next()来循环浏览Iterator

4.2. Iterator and keySet()

4.2.IteratorkeySet()

Similarly, we can iterate through the Map using an Iterator and keySet():

同样地,我们可以使用IteratorkeySet()来迭代Map

public void iterateUsingIteratorAndKeySet(Map<String, Integer> map) {
    Iterator<String> iterator = map.keySet().iterator();
    while (iterator.hasNext()) {
        String key = iterator.next();
        System.out.println(key + ":" + map.get(key));
    }
}

4.3. Iterator and values()

4.3.Iteratorvalues()

We can also walk through the map’s values using an Iterator and the values() method:

我们还可以使用Iteratorvalues()方法浏览地图的值。

public void iterateUsingIteratorAndValues(Map<String, Integer> map) {
    Iterator<Integer> iterator = map.values().iterator();
    while (iterator.hasNext()) {
        Integer value = iterator.next();
        System.out.println("value :" + value);
    }
}

5. Using Lambdas and Stream API

5.使用Lambdas和流API

Since version 8, Java has introduced the Stream API and lambdas. Next, let’s see how to iterate a map using these techniques.

从第8版开始,Java引入了Stream API和lambdas。接下来,让我们看看如何使用这些技术来迭代一个地图。

5.1. Using forEach() and Lambda

5.1.使用forEach()和Lambda

Like most other things in Java 8, this turns out to be much simpler than the alternatives. We’ll just make use of the forEach() method:

就像Java 8中的大多数其他事情一样,这被证明比其他方法简单得多。我们只需使用forEach()方法就可以了。

public void iterateUsingLambda(Map<String, Integer> map) {
    map.forEach((k, v) -> System.out.println((k + ":" + v)));
}

In this case, we don’t need to convert a map to a set of entries. To learn more about lambda expressions, we can start here.

在这种情况下,我们不需要将一个地图转换为一组条目。要了解更多关于lambda表达式的信息,我们可以从这里开始

We can, of course, start from the keys to iterate over the map:

当然,我们可以从钥匙开始,对地图进行迭代。

public void iterateByKeysUsingLambda(Map<String, Integer> map) {
    map.keySet().foreach(k -> System.out.println((k + ":" + map.get(k))));
}

Similarly, we can use the same technique with the values() method:

同样地,我们可以对values()方法使用同样的技术。

public void iterateValuesUsingLambda(Map<String, Integer> map) {
    map.values().forEach(v -> System.out.println(("value: " + v)));
}

5.2. Using Stream API

5.2.使用Stream API

Stream API is one significant feature of Java 8. We can use this feature to loop through a Map as well.

Stream API是Java 8的一个重要特性。我们也可以使用这个功能来循环浏览Map

Stream API should be used when we’re planning on doing some additional Stream processing; otherwise, it’s just a simple forEach() as described previously.

Stream API应该在我们计划做一些额外的Stream处理时使用;否则,它只是一个简单的forEach(),就像之前描述的那样。

Let’s take entrySet() as the example to see how Stream API works:

让我们以entrySet()为例来看看Stream API是如何工作的。

public void iterateUsingStreamAPI(Map<String, Integer> map) {
    map.entrySet().stream()
      // ... some other Stream processings
      .forEach(e -> System.out.println(e.getKey() + ":" + e.getValue()));
}

The usage of Stream API with the keySet() and values() methods would be pretty similar to the example above.

Stream API的使用方法keySet()values()将与上面的例子相当类似。

6. Conclusion

6.结论

In this article, we focused on a critical but straightforward operation: iterating through the entries of a Map.

在这篇文章中,我们重点讨论了一个关键但简单的操作:迭代Map的条目。

We explored a couple of methods that can only be used with Java 8+, namely Lambda expressions and the Stream API.

我们探索了一些只能在Java 8+中使用的方法,即Lambda表达式和Stream API。

As always, the code examples in this article can be found over on GitHub.

一如既往,本文中的代码示例可以在GitHub上找到over