Guava – Maps – 番石榴 – 地图

最后修改: 2014年 11月 6日

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

1. Overview

1.概述

In this tutorial we’ll illustrate the most useful ways you can leverage Guava to work with Java Maps.

在本教程中,我们将说明你可以利用Guava来处理Java Maps的最有用方法。

Let’s start very simple and create a HashMap without the new operator, using Guava:

让我们从非常简单的开始,使用Guava创建一个HashMap,不用new操作符。

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

2. ImmutableMap

2.ImmutableMap

Next – let’s see how to create ImmutableMap using Guava:

接下来–让我们看看如何使用Guava创建ImmutableMap

@Test
public void whenCreatingImmutableMap_thenCorrect() {
    Map<String, Integer> salary = ImmutableMap.<String, Integer> builder()
      .put("John", 1000)
      .put("Jane", 1500)
      .put("Adam", 2000)
      .put("Tom", 2000)
      .build();

    assertEquals(1000, salary.get("John").intValue());
    assertEquals(2000, salary.get("Tom").intValue());
}

3. SortedMap

3.SortedMap

Now – let’s take a look at creating and working with a SortedMap.

现在–让我们看看如何创建和使用SortedMap

In the following example – we’re creating a sorted map using the corresponding Guava builder:

在下面的例子中–我们正在使用相应的Guava构建器创建一个排序的地图。

@Test
public void whenUsingSortedMap_thenKeysAreSorted() {
    ImmutableSortedMap<String, Integer> salary = new ImmutableSortedMap
      .Builder<String, Integer>(Ordering.natural())
      .put("John", 1000)
      .put("Jane", 1500)
      .put("Adam", 2000)
      .put("Tom", 2000)
      .build();

    assertEquals("Adam", salary.firstKey());
    assertEquals(2000, salary.lastEntry().getValue().intValue());
}

4. BiMap

4.BiMap

Next – let’s discuss how to use BiMap. We can use BiMap to map keys back to values as it makes sure the values are unique.

接下来–让我们讨论如何使用BiMap。我们可以使用BiMap将键映射回值,因为它能确保值是唯一的。

In the following example – we create a BiMap and the we get its inverse():

在下面的例子中,我们创建了一个BiMap,然后我们得到了它的inverse()

@Test
public void whenCreateBiMap_thenCreated() {
    BiMap<String, Integer> words = HashBiMap.create();
    words.put("First", 1);
    words.put("Second", 2);
    words.put("Third", 3);

    assertEquals(2, words.get("Second").intValue());
    assertEquals("Third", words.inverse().get(3));
}

5. Multimap

5.Multimap

Now – let’s take a look at Multimap.

现在–让我们看一下Multimap

We can use Multimap to associate each key with multiple values as in the following example:

我们可以使用Multimap将每个键与多个值相关联,如下例所示。

@Test
public void whenCreateMultimap_thenCreated() {
    Multimap<String, String> multimap = ArrayListMultimap.create();
    multimap.put("fruit", "apple");
    multimap.put("fruit", "banana");
    multimap.put("pet", "cat");
    multimap.put("pet", "dog");

    assertThat(multimap.get("fruit"), containsInAnyOrder("apple", "banana"));
    assertThat(multimap.get("pet"), containsInAnyOrder("cat", "dog"));
}

5. Table

5.表格

Let’s now take a look at the Guava Table; we use Table if we need more than one key to index a value.

现在让我们来看看Guava的Table;如果我们需要一个以上的键来索引一个值,我们就使用Table

In the following example – we’re going to use a table to store the distances between cities:

在下面的例子中–我们将使用一个表来存储城市之间的距离。

@Test
public void whenCreatingTable_thenCorrect() {
    Table<String,String,Integer> distance = HashBasedTable.create();
    distance.put("London", "Paris", 340);
    distance.put("New York", "Los Angeles", 3940);
    distance.put("London", "New York", 5576);

    assertEquals(3940, distance.get("New York", "Los Angeles").intValue());
    assertThat(distance.columnKeySet(), 
      containsInAnyOrder("Paris", "New York", "Los Angeles"));
    assertThat(distance.rowKeySet(), containsInAnyOrder("London", "New York"));
}

We can also use Tables.transpose() to flip the row and column keys as in the following example:

我们也可以使用Tables.transpose()来翻转行和列的键值,如下例所示。

@Test
public void whenTransposingTable_thenCorrect() {
    Table<String,String,Integer> distance = HashBasedTable.create();
    distance.put("London", "Paris", 340);
    distance.put("New York", "Los Angeles", 3940);
    distance.put("London", "New York", 5576);

    Table<String, String, Integer> transposed = Tables.transpose(distance);

    assertThat(transposed.rowKeySet(), 
      containsInAnyOrder("Paris", "New York", "Los Angeles"));
    assertThat(transposed.columnKeySet(), containsInAnyOrder("London", "New York"));
}

6. ClassToInstanceMap

6.ClassToInstanceMap

Next – Let’s take a look at ClassToInstanceMap. We can use ClassToInstanceMap if we want the object’s class to be the key as in the following example:

接下来–让我们看看ClassToInstanceMap。如果我们想让对象的类成为关键,我们可以使用ClassToInstanceMap,如下面的例子。

@Test
public void whenCreatingClassToInstanceMap_thenCorrect() {
    ClassToInstanceMap<Number> numbers = MutableClassToInstanceMap.create();
    numbers.putInstance(Integer.class, 1);
    numbers.putInstance(Double.class, 1.5);

    assertEquals(1, numbers.get(Integer.class));
    assertEquals(1.5, numbers.get(Double.class));
}

7. Group List Using Multimap

7.使用Multimap进行分组List

Next – let’s see how to group a List using Multimap. In the following example – we group a List of names by their length using Multimaps.index():

接下来–让我们看看如何使用MultimapList分组。在下面的例子中–我们使用Multimaps.index()将一个List的名字按其长度分组。

@Test
public void whenGroupingListsUsingMultimap_thenGrouped() {
    List<String> names = Lists.newArrayList("John", "Adam", "Tom");
    Function<String,Integer> func = new Function<String,Integer>(){
        public Integer apply(String input) {
            return input.length();
        }
    };
    Multimap<Integer, String> groups = Multimaps.index(names, func);

    assertThat(groups.get(3), containsInAnyOrder("Tom"));
    assertThat(groups.get(4), containsInAnyOrder("John", "Adam"));
}

8. Conclusion

8.结论

In this quick tutorial we discussed the most common and useful usecases of working with Maps using the Guava library.

在这个快速教程中,我们讨论了使用Guava库处理地图的最常见和最有用的使用情况

The implementation of all these examples and code snippets can be found in my Guava GitHub project – this is an Eclipse-based project, so it should be easy to import and run as it is.

所有这些例子和代码片段的实现可以在我的Guava GitHub项目 – 这是一个基于Eclipse的项目,所以它应该很容易导入和运行。