
- Commons Collections 教程
- Commons Collections - 首頁
- Commons Collections - 總覽
- Commons Collections - 環境設定
- Commons Collections - Bag 介面
- Commons Collections - BidiMap 介面
- Commons Collections - MapIterator 介面
- Commons Collections - OrderedMap 介面
- Commons Collections - 忽略 Null
- Commons Collections - 合併與排序
- Commons Collections - 物件轉換
- Commons Collections - 過濾物件
- Commons Collections - 安全空檢查
- Commons Collections - 包含
- Commons Collections - 交集
- Commons Collections - 差集
- Commons Collections - 並集
- Commons Collections 資源
- Commons Collections - 快速指南
- Commons Collections - 有用資源
- Commons Collections - 討論
Commons Collections - 物件轉換
Apache Commons Collections 庫的 CollectionUtils 類為廣泛的使用案例提供了用於常見操作的各種實用方法。它有助於避免編寫樣板程式碼。在 jdk 8 之前,此庫非常有用,因為 Java 8 的 Stream API 中提供了類似的功能。
轉換列表
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 − 用於獲取輸入的集合,不能為空。
Transformer − 要使用的轉換器,可以為空。
返回值
轉換後的結果(新列表)。
異常
NullPointerException − 如果輸入集合為空。
示例
以下示例演示了 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]
廣告