Using the Map.Entry Java Class – 使用Map.Entry Java类

最后修改: 2021年 1月 29日

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

1. Overview

1.概述

We often use maps to store a collection of key-value pairs. Then, at some point, we often need to iterate over them.

我们经常使用地图来存储键值对的集合。然后,在某些时候,我们经常需要对它们进行迭代

In this tutorial, we’ll compare different methods of map iteration, highlighting when it may be beneficial to use Map.Entry. Then, we’ll learn how Map.Entry can be used to create a tuple. Finally, we’ll create an ordered list of tuples.

在本教程中,我们将比较不同的地图迭代方法,强调何时使用Map.Entry可能是有益的。然后,我们将学习如何使用Map.Entry来创建一个元组。最后,我们将创建一个有序的元组列表。

2. Optimizing Map Iteration

2.优化Map迭代

Suppose that we have a map of book titles with the author’s name as the key:

假设我们有一张以作者姓名为关键的书名图。

Map<String, String> map = new HashMap<>();

map.put("Robert C. Martin", "Clean Code");
map.put("Joshua Bloch", "Effective Java");

Let’s compare two methods of getting all the keys and values from our map.

让我们比较一下从我们的地图中获取所有键和值的两种方法。

2.1. Using Map.keySet

2.1.使用Map.keySet

First, consider the following:

首先,考虑以下几点。

for (String key : bookMap.keySet()) {
    System.out.println("key: " + key + " value: " + bookMap.get(key));
}

Here, the loop iterates over keySet. For each key, we get the corresponding value using Map.get. While this is an obvious way to use all of the entries in the map, it requires two operations for each entry — one to get the next key and one to look up the value with get.

这里,循环遍历keySet。对于每个键,我们使用Map.get获得相应的值。虽然这是使用地图中所有条目的明显方法,但它需要对每个条目进行两次操作–一次是获取下一个键,一次是用get查询值。

If we need just the keys in a map, keySet is a good option. However, there’s a faster way to get both the keys and values.

如果我们只需要地图中的键, keySet是一个不错的选择。然而,有一种更快的方法可以同时获得键和值。

2.2. Using Map.entrySet Instead

2.2.使用Map.entrySet代替

Let’s rewrite our iteration to use entrySet:

让我们重写我们的迭代,使用entrySet

for (Map.Entry<String, String> book: bookMap.entrySet()) {
    System.out.println("key: " + book.getKey() + " value: " + book.getValue());
}

In this example, our loop is over a collection of Map.Entry objects. As Map.Entry stores both the key and value together in one class, we get them both in a single operation.

在这个例子中,我们的循环是在一个Map.Entry对象的集合上。由于Map.Entry在一个类中同时存储了键和值,我们在一个操作中得到它们

The same rules apply to using Java 8 stream operations. Streaming over the entrySet and working with Entry objects is more efficient and can require less code.

同样的规则适用于使用 Java 8 流操作。通过entrySet进行流操作并使用Entry对象的效率更高,所需的代码也更少。

3. Working With Tuples

3.使用图元工作

A tuple is a data structure that has a fixed number and order of elements. We can think of Map.Entry is a tuple that stores two elements – a key and a value. However, as Map.Entry is an interface, we require an implementation class. In this section, we’ll explore one implementation provided by the JDK: AbstractMap.SimpleEntry.

元组是一种数据结构,它有固定的元素数量和顺序。我们可以认为Map.Entry是一个存储两个元素的元组–一个键和一个值。然而,由于Map.Entry是一个接口,我们需要一个实现类。在本节中,我们将探讨JDK提供的一个实现:AbstractMap.SimpleEntry

3.1. Creating a Tuple

3.1.创建一个元组

First, consider the Book class:

首先,考虑Book类。

public class Book {
    private String title;
    private String author;

    public Book(String title, String author) {
        this.title = title;
        this.author = author;
    }
    ...

Next, let’s create a Map.Entry tuple with the ISBN as the key and the Book object as the value:

接下来,让我们创建一个Map.Entry元组,以ISBN为键,Book对象为值。

Map.Entry<String, Book> tuple;

Finally, let’s instantiate our tuple with AbstractMap.SimpleEntry:

最后,让我们用AbstractMap.SimpleEntry来实例化我们的元组。

tuple = new AbstractMap.SimpleEntry<>("9780134685991", new Book("Effective Java 3d Edition", "Joshua Bloch"));

3.2. Creating an Ordered List of Tuples

3.2.创建一个有序的图元列表

When working with tuples, it’s often useful to have them as an ordered list.

在处理图元时,将它们作为一个有序的列表往往很有用。

First, we’ll define our list of tuples:

首先,我们将定义我们的图元列表。

List<Map.Entry<String, Book>> orderedTuples = new ArrayList<>();

Secondly, let’s add some entries to our list:

其次,让我们为我们的名单添加一些条目。

orderedTuples.add(new AbstractMap.SimpleEntry<>("9780134685991", 
  new Book("Effective Java 3d Edition", "Joshua Bloch")));
orderedTuples.add(new AbstractMap.SimpleEntry<>("9780132350884", 
  new Book("Clean Code","Robert C Martin")));

3.3. Comparing With a Map

3.3.与Map进行比较

In order to compare the differences with a Map, let’s add a new entry with a key that already exists:

为了比较与Map的差异,让我们用一个已经存在的键添加一个新条目。

orderedTuples.add(new AbstractMap.SimpleEntry<>("9780132350884", 
  new Book("Clean Code", "Robert C Martin")));

Secondly, we’ll iterate over our list, displaying all the keys and values:

其次,我们将对我们的列表进行迭代,显示所有的键和值。

for (Map.Entry<String, Book> tuple : orderedTuples) {
    System.out.println("key: " + tuple.getKey() + " value: " + tuple.getValue());
}

Finally, let’s see the output:

最后,让我们看看输出结果。

key: 9780134685991 value: Book{title='Effective Java 3d Edition', author='Joshua Bloch'}
key: 9780132350884 value: Book{title='Clean Code', author='Robert C Martin'}
key: 9780132350884 value: Book{title='Clean Code', author='Robert C Martin'}

Notice that we can have duplicate keys, unlike a basic Map, where each key has to be unique. This is because we’ve used a List implementation to store our SimpleEntry objects, which means all the objects are independent of each other.

请注意,我们可以有重复的键,而不像基本的Map那样,每个键必须是唯一的。这是因为我们使用了一个List实现来存储我们的SimpleEntry对象,这意味着所有对象都是相互独立的。

3.4. Lists of Entry Objects

3.4.Entry对象的列表

We should note that the purpose of Entry is not to act as a generic tuple. Library classes often provide a generic Pair class for this purpose.

我们应该注意,Entry的目的不是作为一个通用元组。库类通常提供一个通用的Pair类来实现这一目的。

However, we may find that we need to temporarily work with lists of entries while preparing data for a Map or extracting data from one.

然而,我们可能会发现,在为Map准备数据或从其中提取数据时,我们需要临时处理条目列表。

4. Conclusion

4.总结

In this article, we looked at Map.entrySet as an alternative to iterating over a map’s keys.

在这篇文章中,我们研究了Map.entrySet,作为在地图的键上进行迭代的一种替代方法。

We then looked at how Map.Entry can be used as a tuple.

然后我们看了一下Map.Entry如何作为一个元组使用。

Finally, we created a list of ordered tuples, comparing the differences to a basic Map.

最后,我们创建了一个有序图元的列表,比较了与基本Map的差异。

As always, the example code is available over on GitHub.

像往常一样,示例代码可在GitHub上获得