JavaのCollectors.toCollection()メソッドの使い方を徹底解説
JavaのCollectors.toCollection()メソッドは、ストリームの入力要素を出現順(エンカウンター順)に新しいCollectionへ蓄積するCollectorを返します。toList()やtoSet()と異なり、ArrayListやTreeSetなど、任意のコレクション型を自由に指定できるのが大きな特徴です。
toCollection()メソッドの構文
static <T,C extends Collection<T>>
Collector<T,?,C> toCollection(Supplier<C> collectionFactory)
パラメータの説明
- T: 入力要素の型
- C: 結果として生成されるCollectionの型
- Supplier: 結果を供給するための関数型インターフェース
- collectionFactory: 適切な型の新しい空のコレクションを返すSupplier
使用例1:数値文字列をTreeSetに収集する
まずは基本的な例を見てみましょう。
import java.util.Collection;
import java.util.TreeSet;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Demo {
public static void main(String[] args) {
Stream<String> stream = Stream.of("25", "10", "15", "20", "25");
Collection<String> collection = stream.collect(Collectors.toCollection(TreeSet::new));
System.out.println("Collection = "+collection);
}
}
実行結果
Collection = [10, 15, 20, 25]
この例では、重複していた「25」が自動的に除外され、要素が自然順序(昇順)でソートされて格納されています。これはTreeSetがSortedSetを実装しており、重複を許さず常に整列状態を保つためです。
使用例2:名前のリストをTreeSetに収集する
続いて、文字列のストリームを扱う別の例です。
import java.util.Collection;
import java.util.TreeSet;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Demo {
public static void main(String[] args) {
Stream<String> stream = Stream.of("Jack", "Tom", "Brad", "Tim", "Kevin", "Bradley", "Ryan");
Collection<String> collection = stream.collect(Collectors.toCollection(TreeSet::new));
System.out.println("Collection = "+collection);
}
}
実行結果
Collection = [Brad, Bradley, Jack, Kevin, Ryan, Tim, Tom]
7つの名前がアルファベット順にソートされて出力されていることが確認できます。
まとめ
Collectors.toCollection()メソッドを使用すると、標準のtoList()やtoSet()では実現できない、LinkedListやTreeSetなど特定のコレクション型への柔軟な収集が可能になります。特に、ソート済みかつ重複なしのコレクションが必要なケースでは、TreeSet::newを指定するだけで簡単に実現できるので、ぜひ活用してみてください。
-
JavaでIterableをStreamに変換する方法
Javaでは、StreamSupport.stream()メソッドを使うことで、Iterableを簡単にStreamへ変換できます。この記事では、その具体的な手順をサンプルコードとともに解説します。変換の基本手順まず、変換元となるIterableを用意します。以下は文字列のリストから生成した例です。Iterable<String> i = Arrays.asList(K, L, M, N, O, P);次に、独自に定義したconvertIterable()メソッドを呼び出して、Streamを作成します。Stream<String> s = convertIterable
-
JavaでIterableをCollectionに変換する方法
まず、次のようなIterableがあるとします。 Iterable<Integer> i = Arrays.asList(50, 100, 150, 200, 250, 300, 500, 800, 1000); 次に、このIterableをCollectionに変換します。 Collection<Integer> c = convertIterable(i); ここでは、変換処理を行うためのカスタムメソッドconvertIterable()を使用しています。メソッドの実装は以下の通りです。 public static <T> Collection<