Create an Empty Map in Java – 在Java中创建一个空的地图

最后修改: 2022年 2月 21日

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

 1. Overview

1.概述

In this article, we’ll explore the different possible ways of initializing an empty Map in Java.

在这篇文章中,我们将探讨在Java中初始化一个空Map的不同可能方式。

We’ll be using Java 8 as well as Java 9 for checking out the different ways.

我们将使用Java 8以及Java 9来检查不同的方式。

2. Using Java Collections

2.使用Java集合

We can create an empty Map using the emptyMap() method provided by the Java Collections module. This will form an empty Map that is serializable in nature. The method was introduced in Java 1.5 under the Collections Library. This will create an immutable Map:

我们可以使用Java集合模块提供的emptyMap()方法创建一个空Map这将形成一个空的Map,其性质是可序列化的。该方法是在Java 1.5的集合库下引入的。这将创建一个不可变的Map

Map<String, String> emptyMap = Collections.emptyMap();

Note: Since the Map created is immutable in nature it will not allow the user to add any entries or perform any type of modifications to the Map. This will throw a java.lang.UnsupportedOperationException on trying to add or modify any key-value pair in the Map.

注意:由于创建的Map在本质上是不可改变的,它将不允许用户添加任何条目或对Map进行任何类型的修改。这将在试图添加或修改Map中的任何键值对时抛出java.lang.UnsupportedOperationException

We have two more methods that support the creation and initialization of an empty Map. The emptySortedMap() returns an empty SortedMap of immutable type. A SortedMap is one that provides the further total ordering on its keys. The Map created by this method is serializable in nature:

我们还有两个方法支持创建和初始化一个空的MapemptySortedMap()返回一个不可变类型的空SortedMap一个SortedMap是一个在其键上提供进一步的总排序。由这个方法创建的Map在本质上是可序列化的。

SortedMap<String, String> sortedMap = Collections.emptySortedMap();

The other method provided by Java Collections is emptyNavigableMap() which returns an empty NavigableMap. It has the same properties as that of an empty sorted Map. The only difference being this method returns a navigable Map. A Navigable Map is an extension of the traditional sorted Map implementation that returns the closest matches for a given search target.

Java Collections提供的另一个方法是emptyNavigableMap(),它返回一个空的NavigableMap它的属性与空的排序Map相同。唯一的区别是这个方法返回一个可导航的MapNavigable Map是传统的排序Map实现的扩展,它返回给定搜索目标的最接近的匹配。

NavigableMap<String, String> navigableMap = Collections.emptyNavigableMap();

All the above methods return Maps that are immutable in nature and we won’t be able to add any new entries to these Maps. This throws UnsupportedOperationException on forcefully trying to add, delete or modify any key-value pairs.

所有上述方法返回的Maps在本质上是不可改变的,我们将无法向这些Maps添加任何新条目。在强行尝试添加、删除或修改任何键值对时,会抛出UnsupportedOperationException

3. Initializing Map Using Constructors

3.使用构造函数初始化地图

We can initialize Maps using constructors of the different Map implementations i.e. HashMap, LinkedHashMap, TreeMap. All these initializations create an empty Map to which we can add entries later if required:

我们可以使用不同的Map实现的构造函数来初始化Maps,即HashMap, LinkedHashMap, TreeMap。所有这些初始化都会创建一个空的Map,如果需要,我们可以在以后添加条目。

Map hashMap = new HashMap();
Map linkedHashMap = new LinkedHashMap();
Map treeMap = new TreeMap();

The above Maps are mutable and can accept new entries which is one of the advantages of using this approach. The Maps created during this type of initialization are empty. We can define empty Maps in a static block of code.

上述Maps是可变的,可以接受新的条目,这是使用这种方法的优势之一。在这种类型的初始化期间创建的Maps是空的。我们可以在代码的静态块中定义空的Maps

4. The Java 9 Way With Map.of()

4.Java 9的方法是Map.of()

Java 9 comes along with many new features such as Interface Private Methods, Anonymous classes, Platform Module System, and many more. The Map.of() is a factory method that was introduced in the Java 9 version. This method returns an immutable Map that creates zero mappings. The interface provided by this method comes under the Java Collections Framework. The Map.of(key1, value1, key2, value2, …..) can have at max 10 key-value pairs only.

Java 9伴随着许多新的功能,如界面私有方法、匿名类、平台模块系统,等等。Map.of()是Java 9版本中引入的一个工厂方法。该方法返回一个不可变的Map,它可以创建零映射。该方法所提供的接口属于Java集合框架Map.of(key1, value1, key2, value2, …..)最多只能有10个键-值对。

For initializing an empty Map, we’ll not pass any key-value pair in this method:

对于初始化一个空的Map,我们将不在这个方法中传递任何键值对。

Map<String, String> emptyMapUsingJava9 = Map.of();

This factory method produces an immutable Map, hence we’ll not be able to add, delete or modify any key-value pair. An UnsupportedOperationException is thrown on trying to make any mutations in the Map after initialization. The. addition or the deletion of key-value pairs is also not supported and will result in throwing the above exception.

这个工厂方法产生了一个不可变的Map,因此我们将无法添加、删除或修改任何键值对。在初始化后试图对Map进行任何突变时,会抛出一个UnsupportedOperationException。增加或删除键值对也不被支持,并将导致抛出上述异常。

Note: The Map.of() method from Java 9 simplifies the initialization of immutable Maps with desired key-value pairs.

注意:Java 9的Map.of()方法简化了用所需的键值对初始化不可变的Maps

5. Using Guava

5.使用番石榴

Until now we’ve looked into different ways of initializing an empty Map using core Java. Let’s move ahead now and check how to initialize a Map using the Guava library:

到目前为止,我们已经研究了使用核心Java初始化一个空Map的不同方法。现在让我们继续前进,看看如何使用Guava库初始化一个Map

Map<String, String> articles = ImmutableMap.of();

The above method would create an immutable empty Map using the Guava Library.

上述方法将使用Guava库创建一个不可变的空Map

In certain cases, we don’t need an immutable Map. We can initialize a mutable Map using the Maps class:

在某些情况下,我们不需要一个不可变的Map。我们可以使用Maps类来初始化一个可变的Map

Map<String, String> emptyMap = Maps.newHashMap();

This type of initialization creates a mutable Map, i.e. we can add entries to this Map. But the basic initialization of this Map is empty and does not contain any entries.

这种类型的初始化创建了一个可变的Map,也就是说,我们可以向这个Map添加条目。但是这个Map的基本初始化是空的,不包含任何条目。

We can also initialize the Map with specific key and value types. This will create a Map with predefined elements type and throw an exception if not followed:

我们也可以用特定的键和值类型初始化Map。这将创建一个具有预定义元素类型的Map,如果不遵循,则抛出一个异常。

Map genericEmptyMap = Maps.<String, Integer>newHashMap();

In short, this creates an empty Map with key as string and value as an integer. The pair of angle brackets used for initialization is known as the Diamond Syntax. This will create a Map with the defined type arguments that invokes the constructor of the Maps class.

简而言之,这将创建一个空的Map,key为字符串,value为整数。用于初始化的一对角括号被称为Diamond语法这将创建一个具有定义的类型参数的Map,调用Maps类的构造函数。

We can also create a mutable Map in guava using the below syntax:

我们也可以用下面的语法在guava中创建一个可变的Map

Map<String, String> emptyMapUsingGuava = Maps.newHashMap(ImmutableMap.of());

In conclusion, the above method creates an empty Map in Java. We can add entries to this Map since it is mutable in nature.

总之,上述方法在Java中创建了一个空的Map。我们可以向这个Map添加条目,因为它的性质是可变的。

The ImmutableMap.of() also overloaded method versions for creating Maps with entries. Since we are creating an empty Map, we don’t need to pass any parameters inside the method parenthesis to use the overloaded methods.

ImmutableMap.of()也是重载的方法版本,用于创建带有条目的Maps。由于我们正在创建一个空的Map,我们不需要在方法括号内传递任何参数来使用重载方法。

7. Conclusion

7.结语

In this article, we have explored the different ways of initializing an Empty Map. We can see that there’s been a huge improvement in this field since Java 9. We have new factory methods for creating and initializing Maps.

在这篇文章中,我们探讨了初始化Empty Map的不同方法。我们可以看到,自Java 9以来,这一领域有了巨大的改进。 我们有了新的工厂方法来创建和初始化Maps/a>。

As always, the complete source code is available over on Github.

一如既往,完整的源代码可在Github上获得。