Javaでリストをマップに変換する方法

Javaでリストをマップに変換する方法

1. 概要

ListMapに変換することは一般的なタスクです。 このチュートリアルでは、これを行うためのいくつかの方法について説明します。

Listの各要素には、結果のMapのキーとして使用される識別子があると想定します。

2. サンプルデータ構造

まず、要素をモデル化しましょう。

public class Animal {
    private int id;
    private String name;

    //  constructor/getters/setters
}

idフィールドは一意であるため、キーにすることができます。

従来の方法で変換を始めましょう。

3. Java 8より前

明らかに、コアJavaメソッドを使用してListMap に変換できます。

public Map convertListBeforeJava8(List list) {
    Map map = new HashMap<>();
    for (Animal animal : list) {
        map.put(animal.getId(), animal);
    }
    return map;
}

変換をテストしてみましょう。

@Test
public void whenConvertBeforeJava8_thenReturnMapWithTheSameElements() {
    Map map = convertListService
      .convertListBeforeJava8(list);

    assertThat(
      map.values(),
      containsInAnyOrder(list.toArray()));
}

4. Java 8を使用

Java 8から、ストリームとCollectorsを使用してListMapに変換できます。

 public Map convertListAfterJava8(List list) {
    Map map = list.stream()
      .collect(Collectors.toMap(Animal::getId, animal -> animal));
    return map;
}

繰り返しますが、変換が正しく行われていることを確認しましょう。

@Test
public void whenConvertAfterJava8_thenReturnMapWithTheSameElements() {
    Map map = convertListService.convertListAfterJava8(list);

    assertThat(
      map.values(),
      containsInAnyOrder(list.toArray()));
}

5. Guavaライブラリの使用

コアJavaのほかに、変換にサードパーティライブラリを使用できます。

5.1. Mavenの構成

まず、pom.xmlに次の依存関係を追加する必要があります。


    com.google.guava
    guava
    23.6.1-jre

このライブラリの最新バージョンは常にhereで見つけることができます。

5.2. Maps.uniqueIndex()による変換

次に、Maps.uniqueIndex()メソッドを使用してListMapに変換しましょう。

public Map convertListWithGuava(List list) {
    Map map = Maps
      .uniqueIndex(list, Animal::getId);
    return map;
}

最後に、変換をテストしましょう。

@Test
public void whenConvertWithGuava_thenReturnMapWithTheSameElements() {
    Map map = convertListService
      .convertListWithGuava(list);

    assertThat(
      map.values(),
      containsInAnyOrder(list.toArray()));
}

6. ApacheCommonsライブラリの使用

Apache Commonsライブラリの メソッドを使用して変換を行うこともできます。

6.1. Mavenの構成

まず、Mavenの依存関係を含めましょう。


    org.apache.commons
    commons-collections4
    4.2

この依存関係の最新バージョンはhereで利用できます。

6.2. MapUtils

次に、MapUtils.populateMap()を使用して変換を行います。

public Map convertListWithApacheCommons2(List list) {
    Map map = new HashMap<>();
    MapUtils.populateMap(map, list, Animal::getId);
    return map;
}

最後に、期待どおりに機能することを確認しましょう。

@Test
public void whenConvertWithApacheCommons2_thenReturnMapWithTheSameElements() {
    Map map = convertListService
      .convertListWithApacheCommons2(list);

    assertThat(
      map.values(),
      containsInAnyOrder(list.toArray()));
}

7. 価値観の対立

idフィールドが一意でない場合に何が起こるかを確認しましょう。

7.1. idsが重複しているAnimalsList

まず、一意でないidsを使用してAnimalsのListを作成しましょう。

@Before
public void init() {

    this.duplicatedIdList = new ArrayList<>();

    Animal cat = new Animal(1, "Cat");
    duplicatedIdList.add(cat);
    Animal dog = new Animal(2, "Dog");
    duplicatedIdList.add(dog);
    Animal pig = new Animal(3, "Pig");
    duplicatedIdList.add(pig);
    Animal cow = new Animal(4, "Cow");
    duplicatedIdList.add(cow);
    Animal goat= new Animal(4, "Goat");
    duplicatedIdList.add(goat);
}

上に示したように、cowgoatは同じidを持っています。

7.2. 動作の確認

Java Map‘s put() method is implemented so that the latest added value overwrites the previous one with the same key

このため、従来の変換とApache CommonsのMapUtils.populateMap()は同じように動作します。

@Test
public void whenConvertBeforeJava8_thenReturnMapWithRewrittenElement() {

    Map map = convertListService
      .convertListBeforeJava8(duplicatedIdList);

    assertThat(map.values(), hasSize(4));
    assertThat(map.values(), hasItem(duplicatedIdList.get(4)));
}

@Test
public void whenConvertWithApacheCommons_thenReturnMapWithRewrittenElement() {

    Map map = convertListService
      .convertListWithApacheCommons(duplicatedIdList);

    assertThat(map.values(), hasSize(4));
    assertThat(map.values(), hasItem(duplicatedIdList.get(4)));
}

ご覧のとおり、goatcowを同じidで上書きします。

それとは異なり、Collectors.toMap() and MapUtils.populateMap() throw IllegalStateException and IllegalArgumentException respectively

@Test(expected = IllegalStateException.class)
public void givenADupIdList_whenConvertAfterJava8_thenException() {

    convertListService.convertListAfterJava8(duplicatedIdList);
}

@Test(expected = IllegalArgumentException.class)
public void givenADupIdList_whenConvertWithGuava_thenException() {

    convertListService.convertListWithGuava(duplicatedIdList);
}

8. 結論

この簡単な記事では、コアJavaといくつかの一般的なサードパーティライブラリを使用して、ListMap, givingの例に変換するさまざまな方法について説明しました。

いつものように、完全なソースコードはover on GitHubで入手できます。