Commons-collections-transforming-objects
提供:Dev Guides
コモンズコレクション-オブジェクトの変換
Apache Commons CollectionsライブラリのCollectionUtilsクラスは、幅広いユースケースをカバーする一般的な操作のためのさまざまなユーティリティメソッドを提供します。 定型コードの記述を避けるのに役立ちます。 同様の機能がJava 8のStream APIで提供されるようになったため、このライブラリはjdk 8より前に非常に便利です。
リストの変換
CollectionUtilsのcollect()メソッドを使用して、あるタイプのオブジェクトのリストを異なるタイプのオブジェクトのリストに変換できます。
宣言
以下はの宣言です
- org.apache.commons.collections4.CollectionUtils.collect()*メソッド
public static <I,O> Collection<O> collect(Iterable<I> inputCollection,
Transformer<? super I,? extends O> transformer)
パラメーター
- inputCollection -入力を取得するコレクションは、nullではない場合があります。
- Transformer -使用するトランスフォーマーはnullの場合があります。
戻り値
変換された結果(新しいリスト)。
例外
- NullPointerException -入力コレクションがnullの場合。
例
次の例は、org.apache.commons.collections4.CollectionUtils.collect()メソッドの使用法を示しています。 Stringから整数値を解析して、文字列のリストを整数のリストに変換します。
import java.util.Arrays;
import java.util.List;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.Transformer;
public class CollectionUtilsTester {
public static void main(String[] args) {
List<String> stringList = Arrays.asList("1","2","3");
List<Integer> integerList = (List<Integer>) CollectionUtils.collect(stringList,
new Transformer<String, Integer>() {
@Override
public Integer transform(String input) {
return Integer.parseInt(input);
}
});
System.out.println(integerList);
}
}
出力
次の結果が出力されます。
[1, 2, 3]