A Guide to Apache Commons Collections CollectionUtils – 阿帕奇共享资源集合指南 CollectionUtils

最后修改: 2017年 7月 11日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

Simply put, the Apache CollectionUtils provides utility methods for common operations which cover a wide range of use cases and helps in avoiding writing boilerplate code. The library targets older JVM releases because currently, similar functionality is provided by the Java 8’s Stream API.

简单地说,ApacheCollectionUtils为常见的操作提供了实用方法,涵盖了广泛的使用案例,有助于避免编写模板代码。该库以较早的JVM版本为目标,因为目前,类似的功能由Java 8的Stream API提供。

2. Maven Dependencies

2.Maven的依赖性

We need to add the following dependency to get going with CollectionUtils:

我们需要添加以下依赖关系,以便使用CollectionUtils:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-collections4</artifactId>
    <version>4.1</version>
</dependency>

The latest version of the library can be found here.

该库的最新版本可以在这里找到。

3. Setup

3.设置

Let’s add Customer and Address classes:

让我们添加客户地址类:

public class Customer {
    private Integer id;
    private String name;
    private Address address;

    // standard getters and setters
}

public class Address {
    private String locality;
    private String city;
   
    // standard getters and setters
}

We will also keep handy the following Customer and List instances ready to test our implementation:

我们还将保留以下Customer List 实例,准备测试我们的实现。

Customer customer1 = new Customer(1, "Daniel", "locality1", "city1");
Customer customer2 = new Customer(2, "Fredrik", "locality2", "city2");
Customer customer3 = new Customer(3, "Kyle", "locality3", "city3");
Customer customer4 = new Customer(4, "Bob", "locality4", "city4");
Customer customer5 = new Customer(5, "Cat", "locality5", "city5");
Customer customer6 = new Customer(6, "John", "locality6", "city6");

List<Customer> list1 = Arrays.asList(customer1, customer2, customer3);
List<Customer> list2 = Arrays.asList(customer4, customer5, customer6);
List<Customer> list3 = Arrays.asList(customer1, customer2);

List<Customer> linkedList1 = new LinkedList<>(list1);

4. CollectionUtils

4.CollectionUtils

Let’s go through some of the most used methods in Apache Commons CollectionUtils class.

让我们来看看Apache Commons CollectionUtils类中一些最常用的方法。

4.1. Adding Only Non-Null Elements

4.1.只添加非空元素

We can use CollectionUtils’s addIgnoreNull method to add only non-null elements to a provided collection.

我们可以使用CollectionUtils的addIgnoreNull方法,只将非空元素添加到提供的集合中。

The first argument to this method is the collection to which we want to add the element and the second argument is the element that we want to add:

这个方法的第一个参数是我们想要添加的元素的集合,第二个参数是我们想要添加的元素。

@Test
public void givenList_whenAddIgnoreNull_thenNoNullAdded() {
    CollectionUtils.addIgnoreNull(list1, null);
 
    assertFalse(list1.contains(null));
}

Notice that the null was not added to the list.

注意,null没有被添加到列表中。

4.2. Collating Lists

4.2.整理名单

We can use collate method to collate two already sorted lists. This method takes both lists, that we want to merge, as arguments and returns a single sorted list:

我们可以使用collate方法来整理两个已经排序的列表。该方法将我们想要合并的两个列表作为参数,并返回一个排序的列表。

@Test
public void givenTwoSortedLists_whenCollated_thenSorted() {
    List<Customer> sortedList = CollectionUtils.collate(list1, list2);

    assertEquals(6, sortedList.size()); 
    assertTrue(sortedList.get(0).getName().equals("Bob"));
    assertTrue(sortedList.get(2).getName().equals("Daniel"));
}

4.3. Transforming Objects

4.3.变换对象

We can use the transform method to transform objects of class A into different objects of class B. This method takes a list of objects of class A and a transformer as arguments.

我们可以使用transform方法将A类的对象转化为B类的不同对象。这个方法接收一个A类对象的列表和一个transformer作为参数。

The result of this operation is a list of objects of class B:

这个操作的结果是一个B类对象的列表。

@Test
public void givenListOfCustomers_whenTransformed_thenListOfAddress() {
    Collection<Address> addressCol = CollectionUtils.collect(list1, 
      new Transformer<Customer, Address>() {
        public Address transform(Customer customer) {
            return customer.getAddress();
        }
    });
    
    List<Address> addressList = new ArrayList<>(addressCol);
    assertTrue(addressList.size() == 3);
    assertTrue(addressList.get(0).getLocality().equals("locality1"));
}

4.4. Filtering Objects

4.4.筛选对象

Using filter we can remove objects which do not satisfy a given condition from a list. The method takes the list as the first argument and a Predicate as its second argument.

使用filter 我们可以从列表中移除不满足给定条件的对象该方法将列表作为第一个参数,将Predicate 作为第二个参数。

The filterInverse method does the opposite. It removes objects from the list when the Predicate returns true.

filterInverse 方法的作用正好相反。Predicate 返回true时,它将从列表中移除对象。

Both filter and filterInverse return true if the input list was modified, i.e. if at least one object was filtered out from the list:

如果输入的列表被修改,即至少有一个对象从列表中被过滤掉,则filterfilterInverse都会返回true

@Test
public void givenCustomerList_WhenFiltered_thenCorrectSize() {
    
    boolean isModified = CollectionUtils.filter(linkedList1, 
      new Predicate<Customer>() {
        public boolean evaluate(Customer customer) {
            return Arrays.asList("Daniel","Kyle").contains(customer.getName());
        }
    });
     
    assertTrue(linkedList1.size() == 2);
}

We can use select and selectRejected if we want the resultant list to be returned rather than a boolean flag.

如果我们希望返回的是结果列表而不是一个布尔标志,我们可以使用select selectRejected

4.5. Checking for Non-Empty

4.5.检查是否为非空的

The isNotEmpty method is quite handy when we want to check if there is at least single element in a list. The other way of checking the same is:

isNotEmpty方法在我们想检查一个列表中是否至少有一个元素时非常方便。另一种检查方法是。

boolean isNotEmpty = (list != null && list.size() > 0);

Though the above line of code does the same, CollectionUtils.isNotEmpty keeps our code cleaner:

虽然上面的这行代码做得很好,但CollectionUtils.isNotEmpty使我们的代码更简洁。

@Test
public void givenNonEmptyList_whenCheckedIsNotEmpty_thenTrue() {
    assertTrue(CollectionUtils.isNotEmpty(list1));
}

The isEmpty does the opposite. It checks whether the given list is null or there are zero elements in the list:

isEmpty的作用正好相反。它检查给定的列表是否为空或者列表中是否有零个元素。

List<Customer> emptyList = new ArrayList<>();
List<Customer> nullList = null;
 
assertTrue(CollectionUtils.isEmpty(nullList));
assertTrue(CollectionUtils.isEmpty(emptyList));

4.6. Checking Inclusion

4.6.检查收录情况

We can use isSubCollection to check if a collection is contained in another collection. isSubCollection takes two collections as arguments and returns true if the first collection is a subcollection of the second collection:

我们可以使用isSubCollection来检查一个集合是否包含在另一个集合中。isSubCollection将两个集合作为参数,如果第一个集合是第二个集合的子集合,则返回true

@Test
public void givenCustomerListAndASubcollection_whenChecked_thenTrue() {
    assertTrue(CollectionUtils.isSubCollection(list3, list1));
}

A collection is sub-collection of another collection if the number of times an object occurs in the first collection is less than or equal to the number of times it occurs in the second collection.

如果一个对象在第一个集合中出现的次数小于或等于它在第二个集合中出现的次数,那么这个集合就是另一个集合的子集合。

4.7. Intersection of Collections

4.7.集合的交集

We can use CollectionUtils.intersection method to get the intersection of two collections. This method takes two collections and returns a collection of elements of which are common in both the input collections:

我们可以使用CollectionUtils.intersection方法来获得两个集合的交集。该方法接收两个集合,并返回两个输入集合中共同的元素集合。

@Test
public void givenTwoLists_whenIntersected_thenCheckSize() {
    Collection<Customer> intersection = CollectionUtils.intersection(list1, list3);
    assertTrue(intersection.size() == 2);
}

The number of times an element occurs in the resultant collection is a minimum of the number of times it occurs in each of the given collections.

一个元素在结果集合中出现的次数是它在每个给定集合中出现次数的最小值。

4.8. Subtracting Collections

4.8.减去收藏品

CollectionUtils.subtract takes two collections as input and returns a collection which contains elements which are there in the first collection but not in the second collection:

CollectionUtils.subtract 将两个集合作为输入,并返回一个集合,该集合中的元素在第一个集合中存在,但在第二个集合中没有。

@Test
public void givenTwoLists_whenSubtracted_thenCheckElementNotPresentInA() {
    Collection<Customer> result = CollectionUtils.subtract(list1, list3);
    assertFalse(result.contains(customer1));
}

The number of times a collection occurs in the result is the number of times it occurs in first collection minus the number of times it occurs in the second collection.

一个集合在结果中出现的次数是它在第一个集合中出现的次数减去它在第二个集合中出现的次数。

4.9. Union of Collections

4.9.收藏品联盟

CollectionUtils.union does the union of two collections and returns a collection which contains all the elements which are there in either the first or the second collection.

CollectionUtils.union 做两个集合的联合,并返回一个集合,其中包含了第一个或第二个集合中的所有元素。

@Test
public void givenTwoLists_whenUnioned_thenCheckElementPresentInResult() {
    Collection<Customer> union = CollectionUtils.union(list1, list2);
 
    assertTrue(union.contains(customer1));
    assertTrue(union.contains(customer4));
}

The number of times an element occurs in the resulting collection is the maximum of the number of times it occurs in each of the given collections.

一个元素在结果集合中出现的次数是它在每个给定集合中出现次数的最大值。

5. Conclusion

5.结论

And we’re done.

我们就完成了。

We went through some of the commonly used methods of CollectionUtils – which is very much useful to avoid boilerplate when we’re working with collections in our Java projects.

我们浏览了CollectionUtils的一些常用方法–这对于我们在Java项目中使用集合时避免模板非常有用。

As usual, the code is available over on GitHub.

像往常一样,代码可在GitHub上获得

Next »

Apache Commons Collections MapUtils

« Previous

Apache Commons Collections BidiMap