Commons Collections 简明教程

Commons Collections - Transforming Objects

Apache Commons Collections 库的 CollectionUtils 类提供各种实用方法,用于涵盖广泛使用场景的常见操作。它有助于避免编写样板代码。在 jdk 8 之前,该库非常有用,因为 Java 8 的 Stream API 中现在提供了类似的功能。

CollectionUtils class of Apache Commons Collections library provides various utility methods for common operations covering wide range of use cases. It helps avoid writing boilerplate code. This library is very useful prior to jdk 8 as similar functionalities are now provided in Java 8’s Stream API.

Transforming a list

可以使用 CollectionUtils 的 collect() 方法转换一种类型对象的列表为不同类型对象的列表。

collect() method of CollectionUtils can be used to transform a list of one type of objects to list of different type of objects.

Declaration

以下是声明:

Following is the declaration for

org.apache.commons.collections4.CollectionUtils.collect() 方法−

org.apache.commons.collections4.CollectionUtils.collect() method −

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

Parameters

  1. inputCollection − The collection to get the input from, may not be null.

  2. Transformer − The transformer to use, may be null.

Return Value

转换后的结果(新列表)。

The transformed result (new list).

Exception

  1. NullPointerException − If the input collection is null.

Example

以下示例展示了 org.apache.commons.collections4.CollectionUtils.collect() 方法的用法。我们将通过从 String 解析整数值,将字符串列表转换为整数列表。

The following example shows the usage of org.apache.commons.collections4.CollectionUtils.collect() method. We’ll transform a list of string to list of integer by parsing the integer value from 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);
   }
}

Output

当您使用代码时,您将获得以下代码 −

When you use the code, you will get the following code −

[1, 2, 3]