Javaでのリストとセット間の変換
1. 概要
このクイックチュートリアルでは、リストとセット間の変換をプレーンJavaから開始し、Guavaと Apache CommonsCollectionsライブラリを使用して見ていきます。最後にJava10で。
この記事は、ここBaeldungの「Java –BacktoBasic」シリーズの一部です。
2. リストをセットに変換します
2.1. プレーンJavaを使用
Javaを使用してリストをセットに変換することから始めましょう。
public void givenUsingCoreJava_whenListConvertedToSet_thenCorrect() {
List<Integer> sourceList = Arrays.asList(0, 1, 2, 3, 4, 5);
Set<Integer> targetSet = new HashSet<>(sourceList);
}
ご覧のとおり、各コレクションのコンストラクターは別のコレクションをソースとして受け入れるため、変換プロセスはタイプセーフで簡単です。
2.2. グアバと
Guavaを使用して同じ変換を行いましょう。
public void givenUsingGuava_whenListConvertedToSet_thenCorrect() {
List<Integer> sourceList = Lists.newArrayList(0, 1, 2, 3, 4, 5);
Set<Integer> targetSet = Sets.newHashSet(sourceList);
}
2.3. ApacheCommonsCollectionsを使用
次に、Commons Collections APIを使用して、ListとSetの間で変換してみましょう。
public void givenUsingCommonsCollections_whenListConvertedToSet_thenCorrect() {
List<Integer> sourceList = Lists.newArrayList(0, 1, 2, 3, 4, 5);
Set<Integer> targetSet = new HashSet<>(6);
CollectionUtils.addAll(targetSet, sourceList);
}
2.4. Java10を使用
追加のオプションの1つは、Java10で導入されたSet.copyOf静的ファクトリメソッドを使用することです。
public void givenUsingJava10_whenListConvertedToSet_thenCorrect() {
List sourceList = Lists.newArrayList(0, 1, 2, 3, 4, 5);
Set targetSet = Set.copyOf(sourceList);
}
この方法で作成されたSetは変更不可であることに注意してください。
3. SetをListに変換します
3.1. プレーンJavaを使用
次に、Java を使用して、セットからリストへのの逆変換を実行しましょう。
public void givenUsingCoreJava_whenSetConvertedToList_thenCorrect() {
Set<Integer> sourceSet = Sets.newHashSet(0, 1, 2, 3, 4, 5);
List<Integer> targetList = new ArrayList<>(sourceSet);
}
3.2. グアバと
Guavaソリューションを使用して同じことを行うことができます。
public void givenUsingGuava_whenSetConvertedToList_thenCorrect() {
Set<Integer> sourceSet = Sets.newHashSet(0, 1, 2, 3, 4, 5);
List<Integer> targetList = Lists.newArrayList(sourceSet);
}
これはJavaのアプローチと非常に似ていますが、コードの重複が少し少なくなっています。
3.3. ApacheCommonsCollectionsを使用
次に、SetとListの間で変換するCommonsCollectionsソリューションを見てみましょう。
public void givenUsingCommonsCollections_whenSetConvertedToList_thenCorrect() {
Set<Integer> sourceSet = Sets.newHashSet(0, 1, 2, 3, 4, 5);
List<Integer> targetList = new ArrayList<>(6);
CollectionUtils.addAll(targetList, sourceSet);
}
3.4. Java10を使用
最後に、Java10で導入されたList.copyOfを使用できます。
public void givenUsingJava10_whenSetConvertedToList_thenCorrect() {
Set<Integer> sourceSet = Sets.newHashSet(0, 1, 2, 3, 4, 5);
List<Integer> targetList = List.copyOf(sourceSet);
}
結果のリストは変更不可であることに注意する必要があります。
4. 結論
これらすべての例とコードスニペットの実装は、GitHubにあります。これはMavenベースのプロジェクトであるため、そのままインポートして実行するのは簡単です。