Apache Commons Collections MapUtils – 阿帕奇共享资源集合 MapUtils

最后修改: 2017年 7月 23日

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

1. Introduction

1.介绍

MapUtils is one of the tools available in the Apache Commons Collections project.

MapUtils是Apache Commons Collections项目中的一个工具。

Simply put, it provides utility methods and decorators to work with java.util.Map and java.util.SortedMap instances.

简单地说,它提供了实用的方法和装饰器来处理java.util.Mapjava.util.SortedMap实例。

2. Setup

2.设置

Let’s start by adding the dependency:

让我们从添加依赖关系开始。

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-collections4</artifactId>
    <version>4.1</version>
</dependency>

3. Utility Methods

3.实用方法

3.1. Creating a Map from an Array

3.1.从数组创建Map

Now, let’s set up arrays that we will use for creating a map:

现在,让我们来设置我们将用于创建地图的数组。

public class MapUtilsTest {
    private String[][] color2DArray = new String[][] {
        {"RED", "#FF0000"},
        {"GREEN", "#00FF00"},
        {"BLUE", "#0000FF"}
    };
    private String[] color1DArray = new String[] {
        "RED", "#FF0000",
        "GREEN", "#00FF00",
        "BLUE", "#0000FF"
    };
    private Map<String, String> colorMap;

    //...
}

Let’s see how we can create a map from a two-dimensional array:

让我们看看我们如何从一个二维数组中创建一个地图。

@Test
public void whenCreateMapFrom2DArray_theMapIsCreated() {
    this.colorMap = MapUtils.putAll(
      new HashMap<>(), this.color2DArray);

    assertThat(
      this.colorMap, 
      is(aMapWithSize(this.color2DArray.length)));
    
    assertThat(this.colorMap, hasEntry("RED", "#FF0000"));
    assertThat(this.colorMap, hasEntry("GREEN", "#00FF00"));
    assertThat(this.colorMap, hasEntry("BLUE", "#0000FF"));
}

We could also use a one-dimensional array. In that case, the array is treated as keys and values in alternate indices:

我们也可以使用一个一维数组。在这种情况下,数组被当作键和值的交替索引。

@Test
public void whenCreateMapFrom1DArray_theMapIsCreated() {
    this.colorMap = MapUtils.putAll(
      new HashMap<>(), this.color1DArray);
    
    assertThat(
      this.colorMap, 
      is(aMapWithSize(this.color1DArray.length / 2)));

    assertThat(this.colorMap, hasEntry("RED", "#FF0000"));
    assertThat(this.colorMap, hasEntry("GREEN", "#00FF00"));
    assertThat(this.colorMap, hasEntry("BLUE", "#0000FF"));
}

3.2. Printing the Content of a Map

3.2.打印地图的内容

Many times while debugging or in debug logs, we would like to print the entire map:

很多时候,在调试时或调试日志中,我们想打印整个地图。

@Test
public void whenVerbosePrintMap_thenMustPrintFormattedMap() {
    MapUtils.verbosePrint(System.out, "Optional Label", this.colorMap);
}

And the result:

而结果是。

Optional Label = 
{
    RED = #FF0000
    BLUE = #0000FF
    GREEN = #00FF00
}

We can also use debugPrint() which additionally prints the data types of the values.

我们还可以使用debugPrint(),它可以额外打印出数值的数据类型。

3.3. Getting Values

3.3.获取数值

MapUtils provides some methods for extracting value from a map for a given key in a null-safe manner.

MapUtils提供了一些方法,用于以null安全的方式从一个给定键的地图中提取值。

For example, getString() gets a String from the Map. The String value is obtained via toString(). We can optionally specify the default value to be returned if the value is null or if the conversion fails:

例如,getString()Map获得一个StringString值是通过toString()获得的。我们可以选择性地指定在值为null或转换失败时要返回的默认值。

@Test
public void whenGetKeyNotPresent_thenMustReturnDefaultValue() {
    String defaultColorStr = "COLOR_NOT_FOUND";
    String color = MapUtils
      .getString(this.colorMap, "BLACK", defaultColorStr);
    
    assertEquals(color, defaultColorStr);
}

Note that these methods are null-safe i.e. they can safely handle the null map parameter:

注意,这些方法是null安全的,即它们可以安全地处理null地图参数。

@Test
public void whenGetOnNullMap_thenMustReturnDefaultValue() {
    String defaultColorStr = "COLOR_NOT_FOUND";
    String color = MapUtils.getString(null, "RED", defaultColorStr);
    
    assertEquals(color, defaultColorStr);
}

Here the color would get the value as COLOR_NOT_FOUND even though the map is null.

这里的color会得到COLOR_NOT_FOUND的值,尽管地图是null

3.4. Inverting the Map

3.4.倒置地图

We can also easily reverse a map:

我们也可以很容易地扭转地图。

@Test
public void whenInvertMap_thenMustReturnInvertedMap() {
    Map<String, String> invColorMap = MapUtils.invertMap(this.colorMap);

    int size = invColorMap.size();
    Assertions.assertThat(invColorMap)
      .hasSameSizeAs(colorMap)
      .containsKeys(this.colorMap.values().toArray(new String[] {}))
      .containsValues(this.colorMap.keySet().toArray(new String[] {}));
}

This would invert the colorMap to:

这将把colorMap反转为

{
    #00FF00 = GREEN
    #FF0000 = RED
    #0000FF = BLUE
}

If the source map associates same value for multiple keys then after inversion one of the values will become a key randomly.

如果源地图为多个键关联了相同的值,那么在反转之后,其中一个值将随机成为一个键。

3.5. Null and Empty Checks

3.5.空值和空检查

isEmpty() method returns true if a Map is null or empty.

isEmpty()方法在Mapnull或空时返回true

safeAddToMap() method prevents addition of null elements to a Map.

safeAddToMap()方法防止向Map.添加空元素。

4. Decorators

4.装饰公司

These methods add additional functionality to a Map.

这些方法为Map.增加了额外的功能。

In most cases, it’s good practice not to store the reference to the decorated Map.

在大多数情况下,好的做法是不存储对装饰地图的引用.

4.1. Fixed-Size Map

4.1.固定尺寸的地图

fixedSizeMap() returns a fixed-size map backed by the given map. Elements can be changed but not added or removed:

fixedSizeMap()返回一个由给定地图支持的固定尺寸地图。元素可以被改变,但不能被添加或删除。

@Test(expected = IllegalArgumentException.class)
public void whenCreateFixedSizedMapAndAdd_thenMustThrowException() {
    Map<String, String> rgbMap = MapUtils
      .fixedSizeMap(MapUtils.putAll(new HashMap<>(), this.color1DArray));
    
    rgbMap.put("ORANGE", "#FFA500");
}

4.2. Predicated Map

4.2.预测的地图

The predicatedMap() method returns a Map ensures that all held elements match the provided predicate:

predicatedMap()方法返回一个Map,确保所有持有的元素与提供的谓词相匹配。

@Test(expected = IllegalArgumentException.class)
public void whenAddDuplicate_thenThrowException() {
    Map<String, String> uniqValuesMap 
      = MapUtils.predicatedMap(this.colorMap, null, 
        PredicateUtils.uniquePredicate());
    
    uniqValuesMap.put("NEW_RED", "#FF0000");
}

Here, we specified the predicate for values using PredicateUtils.uniquePredicate(). Any attempt to insert a duplicate value into this map will result in java.lang.IllegalArgumentException.

在这里,我们使用PredicateUtils.uniquePredicate()来指定值的谓语。任何试图在这个映射中插入重复值的行为都会导致java.lang.IllegalArgumentException

We can implement custom predicates by implementing the Predicate interface.

我们可以通过实现Predicate接口来实现自定义谓词。

4.3. Lazy Map

4.3.懒惰的地图

lazyMap() returns a map where values are initialized when requested.

lazyMap()返回一个地图,其值在请求时被初始化。

If a key passed to this map’s Map.get(Object) method is not present in the map, the Transformer instance will be used to create a new object that will be associated with the requested key:

如果传递给这个地图的Map.get(Object)方法的一个键在地图中不存在,Transformer实例将被用来创建一个新的对象,该对象将与请求的键相关。

@Test
public void whenCreateLazyMap_theMapIsCreated() {
    Map<Integer, String> intStrMap = MapUtils.lazyMap(
      new HashMap<>(),
      TransformerUtils.stringValueTransformer());
    
    assertThat(intStrMap, is(anEmptyMap()));
    
    intStrMap.get(1);
    intStrMap.get(2);
    intStrMap.get(3);
    
    assertThat(intStrMap, is(aMapWithSize(3)));
}

5. Conclusion

5.结论

In this quick tutorial, we have explored the Apache Commons Collections MapUtils class and we looked at various utility methods and decorators that can simplify various common map operations.

在这个快速教程中,我们探讨了Apache Commons Collections MapUtils类,我们看了各种实用方法和装饰器,可以简化各种常见的地图操作。

As usual, the code is available over on GitHub.

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

Next »

Guide to Apache Commons CircularFifoQueue

« Previous

A Guide to Apache Commons Collections CollectionUtils