鍍金池/ 教程/ Linux/ Apache通用集合轉(zhuǎn)換對象
Apache Commons Collections教程
Apache通用集合開發(fā)環(huán)境
Apache通用集合過濾對象
Commons Collections簡介
Apache通用集合聯(lián)合
Apache OrderedMap接口
Apache通用集合Bag接口
Apache通用集合安全空檢查
Apache通用集合差集
Apache通用集合包函關(guān)系
Apache通用集合BidiMap接口
Apache通用集合相交
Apache通用集合轉(zhuǎn)換對象
Apache通用集合合并與排序
Apache通用集合忽略Null
Apache通用集合MapIterator接口

Apache通用集合轉(zhuǎn)換對象

Apache Commons Collections庫的CollectionUtils類提供各種實用方法,用于覆蓋廣泛用例的常見操作。 它有助于避免編寫樣板代碼。 這個庫在jdk 8之前是非常有用的,但現(xiàn)在Java 8的Stream API提供了類似的功能。

轉(zhuǎn)換列表

CollectionUtilscollect()方法可用于將一種類型的對象列表轉(zhuǎn)換為不同類型的對象列表。

聲明

以下是org.apache.commons.collections4.CollectionUtils.collect()方法的聲明 -

public static <I,O> Collection<O> collect(Iterable<I> inputCollection, 
   Transformer<? super I,? extends O> transformer)

參數(shù)

  • inputCollection - 從中獲取輸入的集合可能不為null。
  • transformer - 要使用的transformer可能為null

返回值

  • 換結(jié)果(新列表)。

示例

以下示例顯示org.apache.commons.collections4.CollectionUtils.collect()方法的用法。 將通過解析String中的整數(shù)值來將字符串列表轉(zhuǎn)換為整數(shù)列表。

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);
   }
}

執(zhí)行上面示例代碼,得到以下結(jié)果 -

[1, 2, 3]