Javaにおける配列と集合の間の変換

Javaでの配列とセット間の変換

1. 概要

この短い記事では、converting between an array and a Setについて説明します。最初にプレーンJavaを使用し、次にGuavaとApacheのCommonsCollectionsライブラリを使用します。

この記事は、例としてここのthe “Java – Back to Basic” seriesの一部です。

2. ArraySetに変換します

2.1. プレーンJavaの使用

まず、turn the array to a Set using plain Javaの方法を見てみましょう。

@Test
public void givenUsingCoreJavaV1_whenArrayConvertedToSet_thenCorrect() {
    Integer[] sourceArray = { 0, 1, 2, 3, 4, 5 };
    Set targetSet = new HashSet(Arrays.asList(sourceArray));
}

または、Setを最初に作成してから、配列要素を入力することもできます。

@Test
public void givenUsingCoreJavaV2_whenArrayConvertedToSet_thenCorrect() {
    Integer[] sourceArray = { 0, 1, 2, 3, 4, 5 };
    Set targetSet = new HashSet();
    Collections.addAll(targetSet, sourceArray);
}

2.2. Google Guavaを使用する

次に、the Guava conversion from array to Setを見てみましょう。

@Test
public void givenUsingGuava_whenArrayConvertedToSet_thenCorrect() {
    Integer[] sourceArray = { 0, 1, 2, 3, 4, 5 };
    Set targetSet = Sets.newHashSet(sourceArray);
}

2.3. Apache Commonsコレクションの使用

最後に、ApacheのCommonsCollectionライブラリを使用して変換を行いましょう。

@Test
public void givenUsingCommonsCollections_whenArrayConvertedToSet_thenCorrect() {
    Integer[] sourceArray = { 0, 1, 2, 3, 4, 5 };
    Set targetSet = new HashSet<>(6);
    CollectionUtils.addAll(targetSet, sourceArray);
}

3. セットを配列に変換

3.1. プレーンJavaの使用

次に、その逆を見てみましょう–converting an existing Set to an array

@Test
public void givenUsingCoreJava_whenSetConvertedToArray_thenCorrect() {
    Set sourceSet = Sets.newHashSet(0, 1, 2, 3, 4, 5);
    Integer[] targetArray = sourceSet.toArray(new Integer[sourceSet.size()]);
}

3.2. グアバの使用

次–グアバソリューション:

@Test
public void givenUsingGuava_whenSetConvertedToArray_thenCorrect() {
    Set sourceSet = Sets.newHashSet(0, 1, 2, 3, 4, 5);
    int[] targetArray = Ints.toArray(sourceSet);
}

GuavaのInts APIを使用しているため、このソリューションは、使用しているデータ型に固有であることに注意してください。

3.3 Using Commons Collections

そして最後に、Apache Commons Collectionsライブラリを使用してSetを配列に変換しましょう。

@Test
public void givenUsingCommonsCollections_whenSetConvertedToArray_thenCorrect() {
    Set sourceSet = Sets.newHashSet(0, 1, 2, 3, 4, 5);
    Integer[] targetArray = sourceSet.toArray(new Integer[sourceSet.size()]);
}

4. 結論

これらすべての例とコードスニペットcan be found over on Githubの実装–これはMavenベースのプロジェクトであるため、そのままインポートして実行するのは簡単です。