Commons Collections 简明教程
Apache Commons Collections - Overview
Commons 集合扩展了 Java 集合框架。它提供了若干功能,以简化集合处理。它提供了许多新的接口、实现和实用工具。
Commons Collections augments Java Collections Framework. It provides several features to make collection handling easy. It provides many new interfaces, implementations and utilities.
Commons 集合的主要功能如下:
The main features of Commons Collections are as follows −
-
Bag − Bag interfaces simplifies the collections, which have multiple number of copies of each object.
-
BidiMap − BidiMap interfaces provide Bi-Directional maps, which can be used to lookup values using keys or keys using values.
-
MapIterator − MapIterator interface provide simple and easy iteration over maps.
-
Transforming Decorators − Transforming decorators can alter every object of a collection as and when it is added to the collection.
-
Composite Collections − Composite collections are used, where multiple collections are required to be handled uniformly.
-
Ordered Map − Ordered Maps retain the order, in which elements are added in.
-
Ordered Set − Ordered Sets retain the order, in which elements are added in.
-
Reference map − Reference map allows key/values to be garbage collected under close control.
-
Comparator implementations − Many Comparator implementations are available.
-
Iterator implementations − Many Iterator implementations are available.
-
Adapter Classes − Adapter classes are available to convert array and enumerations to collections.
-
Utilities − Utilities are available to test or create typical set-theory properties of collections such as union, intersection. Supports Closure.
Commons Collections - Environment Setup
Local Environment Setup
如果您仍然愿意为 Java 编程语言设置您的环境,则本节指导您如何在您的机器上下载并设置 Java。请按照下面提到的步骤设置环境。
If you are still willing to set up your environment for Java programming language, then this section guides you on how to download and set up Java on your machine. Please follow the steps mentioned below to set up the environment.
Java SE 可以从 www.oracle.com/technetwork/java/archive-139210.html 链接免费获得。因此,您可以根据自己的操作系统下载一个版本。
Java SE is freely available from the link www.oracle.com/technetwork/java/archive-139210.html So, you download a version based on your operating system.
按照说明下载 Java 并运行 .exe 以在您的机器上安装 Java。在您的机器上安装 Java 后,您需要设置环境变量以指向正确的安装目录。
Follow the instructions to download Java and run the .exe to install Java on your machine. Once, you have installed Java on your machine, you would need to set environment variables to point to correct installation directories.
Setting up the Path for Windows 2000/XP
我们假设您已在 c:\Program Files\java\jdk directory 中安装了 Java。
We are assuming that you have installed Java in c:\Program Files\java\jdk directory
-
Right-click on 'My Computer' and select 'Properties'.
-
Click on the 'Environment variables' button under the 'Advanced' tab.
-
Now, alter the 'Path' variable so that it also contains the path to the Java executable. Example, if the path is currently set to 'C:\WINDOWS\SYSTEM32', then change your path to read 'C:\WINDOWS\SYSTEM32;c:\Program Files\java\jdk\bin'.
Setting up the Path for Windows 95/98/ME
我们假设您已在 c:\Program Files\java\jdk directory 中安装了 Java。
We are assuming that you have installed Java in c:\Program Files\java\jdk directory.
-
Edit the 'C:\autoexec.bat' file and add the following line at the end − 'SET PATH=%PATH%;C:\Program Files\java\jdk\bin'.
Setting up the Path for Linux, UNIX, Solaris, FreeBSD
应设置环境变量 PATH 来指向 Java 二进制文件安装的位置。如果您遇到困难,请参阅您的 Shell 文档。
Environment variable PATH should be set to point to where, the Java binaries have been installed. Refer to your shell documentation, if you have trouble doing this.
例如,如果您使用 bash 作为您的 Shell,则您需要将以下行添加到您的 .bashrc: export PATH=/path/to/java:$PATH' 的末尾:
Example, if you use bash as your shell, then you would add the following line to the end of your '.bashrc: export PATH=/path/to/java:$PATH'
Popular Java Editors
要编写 Java 程序,您需要一个文本编辑器。市场中有许多高级集成开发环境可用。但目前,您可以考虑以下选项之一 −
To write your Java programs, you need a text editor. There are many sophisticated IDEs available in the market. But for now, you can consider one of the following −
-
Notepad − On Windows machine, you can use any simple text editor like Notepad (Recommended for this tutorial), TextPad.
-
Netbeans − It is a Java IDE that is open-source and free, which can be downloaded from www.netbeans.org/index.html.
-
Eclipse − It is also a Java IDE developed by the eclipse open-source community and can be downloaded from www.eclipse.org.
Download Common Collections Archive
从 commons-collections4-4.1-bin.zip 下载 Apache Common Collections jar 文件的最新版本。在撰写本教程时,我们下载了 commons-collections4-4.1-bin.zip 并将其复制到 C:>Apache folder 中。
Download the latest version of Apache Common Collections jar file from commons-collections4-4.1-bin.zip. At the time of writing this tutorial, we have downloaded commons-collections4-4.1-bin.zip and copied it into C:\>Apache folder.
OS |
Archive name |
Windows |
commons-collections4-4.1-bin.zip |
Linux |
commons-collections4-4.1-bin.tar.gz |
Mac |
commons-collections4-4.1-bin.tar.gz |
Set Apache Common Collections Environment
将 APACHE_HOME 环境变量设置到存储在计算机上的 Apache jar 所在的基目录位置。假设我们已在各种操作系统上将 commons-collections4-4.1-bin.zip 抽取到 Apache 文件夹中,如下所示 −
Set the APACHE_HOME environment variable to point to the base directory location where Apache jar is stored on your machine. Assuming, we’ve extracted commons-collections4-4.1-bin.zip in Apache folder on various Operating Systems as follows −
OS |
Archive name |
Windows |
Set the environment variable APACHE_HOME to C:\Apache |
Linux |
export APACHE_HOME=/usr/local/Apache |
Mac |
export APACHE_HOME=/Library/Apache |
Set CLASSPATH Variable
将 CLASSPATH 环境变量设置到 Common Collections jar 位置。假设你已将 commons-collections4-4.1-bin.zip 存储在各种操作系统上的 Apache 文件夹中,如下所示 −
Set the CLASSPATH environment variable to point to the Common Collections jar location. Assuming, you have stored commons-collections4-4.1-bin.zip in Apache folder on various Operating Systems as follows −
OS |
Output |
Windows |
Set the environment variable CLASSPATH to %CLASSPATH%;%APACHE_HOME%\commons-collections4-4.1-bin.jar;.; |
Linux |
export CLASSPATH=$CLASSPATH:$APACHE_HOME/commons-collections4-4.1-bin.jar:. |
Mac |
export CLASSPATH=$CLASSPATH:$APACHE_HOME/commons-collections4-4.1-bin.jar:. |
Apache Commons Collections - Bag Interface
添加了新接口来支持包。包定义了一个集合,它会计算对象在集合中出现的次数。例如,如果一个包包含 {a, a, b, c},那么 getCount("a") 将返回 2,而 uniqueSet() 将返回唯一值。
New Interfaces are added to supports bags. A Bag defines a collection which, counts the number of times an object appears in the collection. For example, if a Bag contains {a, a, b, c} then getCount("a") will return 2 while uniqueSet() returns the unique values.
Interface Declaration
以下是 org.apache.commons.collections4.Bag<E> 接口的声明:
Following is the declaration for org.apache.commons.collections4.Bag<E> interface −
public interface Bag<E>
extends Collection<E>
Methods
包推理的方法如下:
The methods for bag inference are as follows −
Sr.No. |
Method & Description |
1 |
boolean add(E object) (Violation) Adds one copy of the specified object to the Bag. |
2 |
boolean add(E object, int nCopies) Adds nCopies copies of the specified object to the Bag. |
3 |
boolean containsAll(Collection<?> coll) (Violation) Returns true if the bag contains all elements in the given collection, respecting cardinality. |
4 |
int getCount(Object object) Returns the number of occurrences (cardinality) of the given object currently in the bag. |
5 |
Iterator<E> iterator() Returns an Iterator over the entire set of members, including copies due to cardinality. |
6 |
boolean remove(Object object) (Violation) Removes all occurrences of the given object from the bag. |
7 |
boolean remove(Object object, int nCopies) Removes nCopies copies of the specified object from the Bag. |
8 |
boolean removeAll(Collection<?> coll) (Violation) Remove all elements represented in the given collection, respecting cardinality. |
9 |
boolean retainAll(Collection<?> coll) (Violation) Remove any members of the bag that are not in the given collection, respecting cardinality. |
10 |
int size() Returns the total number of items in the bag across all types. |
11 |
Set<E> uniqueSet() Returns a Set of unique elements in the Bag. |
Methods Inherited
此接口继承了以下接口中的方法:
This interface inherits methods from the following interface −
-
java.util.Collectio.
Example of Bag Interface
BagTester.java 的一个示例如下:
An example of BagTester.java is as follows −
import org.apache.commons.collections4.Bag;
import org.apache.commons.collections4.bag.HashBag;
public class BagTester {
public static void main(String[] args) {
Bag<String> bag = new HashBag<>();
//add "a" two times to the bag.
bag.add("a" , 2);
//add "b" one time to the bag.
bag.add("b");
//add "c" one time to the bag.
bag.add("c");
//add "d" three times to the bag.
bag.add("d",3
//get the count of "d" present in bag.
System.out.println("d is present " + bag.getCount("d") + " times.");
System.out.println("bag: " +bag);
//get the set of unique values from the bag
System.out.println("Unique Set: " +bag.uniqueSet());
//remove 2 occurrences of "d" from the bag
bag.remove("d",2);
System.out.println("2 occurences of d removed from bag: " +bag);
System.out.println("d is present " + bag.getCount("d") + " times.");
System.out.println("bag: " +bag);
System.out.println("Unique Set: " +bag.uniqueSet());
}
}
Commons Collections - BidiMap Interface
新接口被添加以支持双向 Map。使用双向 Map,可以使用值来查找键,可以使用键来查找值。
New Interfaces are added to supports bidirectional Map. Using bidirectional map, a key can be lookup using value and value can be lookup using key easily.
Interface Declaration
下面是对 org.apache.commons.collections4.BidiMap<K,V> 接口的声明 −
Following is the declaration for org.apache.commons.collections4.BidiMap<K,V> interface −
public interface BidiMap<K,V>
extends IterableMap<K,V>
Methods
BidiMap 接口的方法如下 −
The methods for the BidiMap Interface are as follows −
Sr.No. |
Method & Description |
1 |
K getKey(Object value) Gets the key that is currently mapped to the specified value. |
2 |
BidiMap<V,K> inverseBidiMap() Gets a view of this map where the keys and values are reversed. |
3 |
V put(K key, V value) Puts the key-value pair into the map, replacing any previous pair. |
4 |
K removeValue(Object value) Removes the key-value pair that is currently mapped to the specified value (optional operation). |
5 |
Set<V> values() Returns a Set view of the values contained in this map. |
Methods Inherited
此接口继承下列接口中的方法-
This interface inherits methods from the following interfaces −
-
org.apache.commons.collections4.Ge.
-
org.apache.commons.collections4.IterableGe.
-
org.apache.commons.collections4.Pu.
-
java.util.Ma.
Example of BidiMap Interface
BidiMapTester.java 的示例如下 −
An example of BidiMapTester.java is as follows −
import org.apache.commons.collections4.BidiMap;
import org.apache.commons.collections4.bidimap.TreeBidiMap;
public class BidiMapTester {
public static void main(String[] args) {
BidiMap>String, String< bidi = new TreeBidiMap<>();
bidi.put("One", "1");
bidi.put("Two", "2");
bidi.put("Three", "3");
System.out.println(bidi.get("One"));
System.out.println(bidi.getKey("1"));
System.out.println("Original Map: " + bidi);
bidi.removeValue("1");
System.out.println("Modified Map: " + bidi);
BidiMap<String, String> inversedMap = bidi.inverseBidiMap();
System.out.println("Inversed Map: " + inversedMap);
}
}
Commons Collections - MapIterator Interface
JDK Map 接口很难迭代,因为迭代必须在 EntrySet 或 KeySet 对象上进行。MapIterator 在 Map 上提供简单的迭代。以下示例对此进行了说明。
The JDK Map interface is pretty difficult to iterate as Iteration to be done on EntrySet or over the KeySet objects. MapIterator provides simple iteration over Map. Following example illustrates the same.
Example of MapIterator Interface
MapIteratorTester.java 的示例如下 −
An example for MapIteratorTester.java is as follows −
import org.apache.commons.collections4.IterableMap;
import org.apache.commons.collections4.MapIterator;
import org.apache.commons.collections4.map.HashedMap;
public class MapIteratorTester {
public static void main(String[] args) {
IterableMap<String, String> map = new HashedMap<>();
map.put("1", "One");
map.put("2", "Two");
map.put("3", "Three");
map.put("4", "Four");
map.put("5", "Five");
MapIterator<String, String> iterator = map.mapIterator();
while (iterator.hasNext()) {
Object key = iterator.next();
Object value = iterator.getValue();
System.out.println("key: " + key);
System.out.println("Value: " + value);
iterator.setValue(value + "_");
}
System.out.println(map);
}
}
Commons Collections - OrderedMap Interface
OrderedMap 是一个新的 Map 接口,用于保留元素添加的顺序。LinkedMap 和 ListOrderedMap 是两个可用的实现。此接口支持 Map 的迭代器,并允许在 Map 中按正向或反向迭代。以下示例对此进行了说明。
OrderedMap is a new interface for maps to retain the order in which elements are added. LinkedMap and ListOrderedMap are two available implementations. This interfaces supports iterator that of Map and allows iteration in both directions either forwards or backwards in a Map. Following example illustrates the same.
Example of MapIterator Interface
OrderedMapTester.java 的示例如下 −
An example of OrderedMapTester.java is as given below −
import org.apache.commons.collections4.OrderedMap;
import org.apache.commons.collections4.map.LinkedMap;
public class OrderedMapTester {
public static void main(String[] args) {
OrderedMap<String, String> map = new LinkedMap<String, String>();
map.put("One", "1");
map.put("Two", "2");
map.put("Three", "3");
System.out.println(map.firstKey());
System.out.println(map.nextKey("One"));
System.out.println(map.nextKey("Two"));
}
}
Apache Commons Collections - Ignore Null
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.
Check for Not Null Elements
CollectionUtils 的 addIgnoreNull() 方法可用于确保仅将非空值添加到集合中。
addIgnoreNull() method of CollectionUtils can be used to ensure that only non-null values are getting added to the collection.
Declaration
以下是声明:
Following is the declaration for
org.apache.commons.collections4.CollectionUtils.addIgnoreNull() 方法 −
org.apache.commons.collections4.CollectionUtils.addIgnoreNull() method −
public static <T> boolean addIgnoreNull(Collection<T> collection, T object)
Parameters
-
collection − The collection to add to, must not be null.
-
object − The object to add, if null it will not be added.
Example
以下示例显示 org.apache.commons.collections4.CollectionUtils.addIgnoreNull() 方法的用法。我们尝试添加一个 null 值和一个非 null 值示例。
The following example shows the usage of org.apache.commons.collections4.CollectionUtils.addIgnoreNull() method. We are trying to add a null value and a sample non-null value.
import java.util.LinkedList;
import java.util.List;
import org.apache.commons.collections4.CollectionUtils;
public class CollectionUtilsTester {
public static void main(String[] args) {
List<String> list = new LinkedList<String>();
CollectionUtils.addIgnoreNull(list, null);
CollectionUtils.addIgnoreNull(list, "a");
System.out.println(list);
if(list.contains(null)) {
System.out.println("Null value is present");
} else {
System.out.println("Null value is not present");
}
}
}
Apache Commons Collections - Merge & Sort
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.
Merging two sorted lists
可使用 CollectionUtils 的 collate() 方法合并两个已排序的列表。
collate() method of CollectionUtils can be used to merge two already sorted lists.
Declaration
以下是声明:
Following is the declaration for
org.apache.commons.collections4.CollectionUtils.collate() 方法 −
org.apache.commons.collections4.CollectionUtils.collate() method −
public static <O extends Comparable<? super O>> List<O>
collate(Iterable<? extends O> a, Iterable<? extends O> b)
Return Value
一个新的已排序列表,包含集合 a 和 b 的元素。
A new sorted List, containing the elements of Collection a and b.
Example
以下示例显示 org.apache.commons.collections4.CollectionUtils.collate() 方法的用法。我们将合并两个已排序列表,然后打印已合并且已排序的列表。
The following example shows the usage of org.apache.commons.collections4.CollectionUtils.collate() method. We’ll merge two sorted lists and then print the merged and sorted list.
import java.util.Arrays;
import java.util.List;
import org.apache.commons.collections4.CollectionUtils;
public class CollectionUtilsTester { 8. Apache Commons Collections — Merge & Sort
public static void main(String[] args) {
List<String> sortedList1 = Arrays.asList("A","C","E");
List<String> sortedList2 = Arrays.asList("B","D","F");
List<String> mergedList = CollectionUtils.collate(sortedList1, sortedList2);
System.out.println(mergedList);
}
}
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
-
inputCollection − The collection to get the input from, may not be null.
-
Transformer − The transformer to use, may be 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);
}
}
Commons Collections - Filtering 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.
filter() method
可使用 CollectionUtils 的 filter() 方法,过滤列表以删除不满足由传递的谓词提供的条件的对象。
filter() method of CollectionUtils can be used to filter a list to remove objects which do not satisfy condition provided by predicate passed.
Declaration
以下是声明:
Following is the declaration for
org.apache.commons.collections4.CollectionUtils.filter() 方法 −
org.apache.commons.collections4.CollectionUtils.filter() method −
public static <T> boolean filter(Iterable<T> collection,
Predicate<? super T> predicate)
Parameters
-
collection − The collection to get the input from, may not be null.
-
predicate − The predicate to use as a filter, may be null.
Return Value
如果此次调用修改了集合,则返回 True,否则返回 False。
True if the collection is modified by this call, false otherwise.
Example
以下示例显示 org.apache.commons.collections4.CollectionUtils.filter() 方法的用法。我们将过滤一个整数列表,以仅获取偶数。
The following example shows the usage of org.apache.commons.collections4.CollectionUtils.filter() method. We’ll filter a list of integer to get even numbers only.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.Predicate;
public class CollectionUtilsTester {
public static void main(String[] args) {
List<Integer> integerList = new ArrayList<Integer>();
integerList.addAll(Arrays.asList(1,2,3,4,5,6,7,8));
System.out.println("Original List: " + integerList);
CollectionUtils.filter(integerList, new Predicate<Integer>() {
@Override
public boolean evaluate(Integer input) {
if(input.intValue() % 2 == 0) {
return true;
}
return false;
}
});
System.out.println("Filtered List (Even numbers): " + integerList);
}
}
filterInverse() method
可使用 CollectionUtils 的 filterInverse() 方法,过滤列表以删除满足由传递的谓词提供的条件的对象。
filterInverse() method of CollectionUtils can be used to filter a list to remove objects, which satisfy condition provided by predicate passed.
Declaration
以下是声明:
Following is the declaration for
org.apache.commons.collections4.CollectionUtils.filterInverse() 方法 −
org.apache.commons.collections4.CollectionUtils.filterInverse() method −
public static <T> boolean filterInverse(Iterable<T> collection, Predicate<? super T> predicate)
Parameters
-
collection − The collection to get the input from, may not be null.
-
predicate − The predicate to use as a filter, may be null.
Return Value
如果此次调用修改了集合,则返回 True,否则返回 False。
True if the collection is modified by this call, false otherwise.
Example
以下示例显示 org.apache.commons.collections4.CollectionUtils.filterInverse() 方法的用法。我们将过滤一个整数列表,以仅获取奇数。
The following example shows the usage of org.apache.commons.collections4.CollectionUtils.filterInverse() method. We’ll filter a list of integer to get odd numbers only.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.Predicate;
public class CollectionUtilsTester {
public static void main(String[] args) {
List<Integer> integerList = new ArrayList<Integer>();
integerList.addAll(Arrays.asList(1,2,3,4,5,6,7,8));
System.out.println("Original List: " + integerList);
CollectionUtils.filterInverse(integerList, new Predicate<Integer>() {
@Override
public boolean evaluate(Integer input) {
if(input.intValue() % 2 == 0) {
return true;
}
return false;
}
});
System.out.println("Filtered List (Odd numbers): " + integerList);
}
}
Commons Collections - Safe Empty Checks
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.
Checking non-empty list
CollectionUtils 的 isNotEmpty() 方法可用于检查一个列表是否不为空,而无需担心列表为 null。因此,在检查列表大小之前不必到处放置 null 检查。
isNotEmpty() method of CollectionUtils can be used to check if a list is not empty without worrying about null list. So null check is not required to be placed everywhere before checking the size of the list.
Declaration
以下是声明:
Following is the declaration for
org.apache.commons.collections4.CollectionUtils.isNotEmpty() 方法 -
org.apache.commons.collections4.CollectionUtils.isNotEmpty() method −
public static boolean isNotEmpty(Collection<?> coll)
Example
以下示例显示了 org.apache.commons.collections4.CollectionUtils.isNotEmpty() 方法的用法。我们将检查一个列表是否为空。
The following example shows the usage of org.apache.commons.collections4.CollectionUtils.isNotEmpty() method. We’ll check a list is empty or not.
import java.util.List;
import org.apache.commons.collections4.CollectionUtils;
public class CollectionUtilsTester {
public static void main(String[] args) {
List<String> list = getList();
System.out.println("Non-Empty List Check: " + checkNotEmpty1(list));
System.out.println("Non-Empty List Check: " + checkNotEmpty1(list));
}
static List<String> getList() {
return null;
}
static boolean checkNotEmpty1(List<String> list) {
return !(list == null || list.isEmpty());
}
static boolean checkNotEmpty2(List<String> list) {
return CollectionUtils.isNotEmpty(list);
}
}
Checking empty list
CollectionUtils 的 isEmpty() 方法可用于检查一个列表是否为空,而无需担心列表为 null。因此,在检查列表大小之前不必到处放置 null 检查。
isEmpty() method of CollectionUtils can be used to check if a list is empty without worrying about null list. So null check is not required to be placed everywhere before checking the size of the list.
Declaration
以下是声明:
Following is the declaration for
org.apache.commons.collections4.CollectionUtils.isEmpty() 方法 -
org.apache.commons.collections4.CollectionUtils.isEmpty() method −
public static boolean isEmpty(Collection<?> coll)
Example
以下示例显示了 org.apache.commons.collections4.CollectionUtils.isEmpty() 方法的用法。我们将检查一个列表是否为空。
The following example shows the usage of org.apache.commons.collections4.CollectionUtils.isEmpty() method. We’ll check a list is empty or not.
import java.util.List;
import org.apache.commons.collections4.CollectionUtils;
public class CollectionUtilsTester {
public static void main(String[] args) {
List<String> list = getList();
System.out.println("Empty List Check: " + checkEmpty1(list));
System.out.println("Empty List Check: " + checkEmpty1(list));
}
static List<String> getList() {
return null;
}
static boolean checkEmpty1(List<String> list) {
return (list == null || list.isEmpty());
}
static boolean checkEmpty2(List<String> list) {
return CollectionUtils.isEmpty(list);
}
}
Apache Commons Collections - Inclusion
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.
Checking sublist
CollectionUtils 的 isSubCollection() 方法可用于检查集合是否包含给定的集合。
isSubCollection() method of CollectionUtils can be used to check if a collection contains the given collection or not.
Declaration
以下是声明:
Following is the declaration for
org.apache.commons.collections4.CollectionUtils.isSubCollection() 方法 −
org.apache.commons.collections4.CollectionUtils.isSubCollection() method −
public static boolean isSubCollection(Collection<?> a, Collection<?> b)
Parameters
-
a − The first (sub) collection, must not be null.
-
b − The second (super) collection, must not be null.
Example
以下示例展示了 org.apache.commons.collections4.CollectionUtils.isSubCollection() 方法的用法。我们将检查一个列表是否是另一个列表的一部分。
The following example shows the usage of org.apache.commons.collections4.CollectionUtils.isSubCollection() method. We’ll check a list is part of another list or not.
import java.util.Arrays;
import java.util.List;
import org.apache.commons.collections4.CollectionUtils;
public class CollectionUtilsTester {
public static void main(String[] args) {
//checking inclusion
List<String> list1 = Arrays.asList("A","A","A","C","B","B");
List<String> list2 = Arrays.asList("A","A","B","B");
System.out.println("List 1: " + list1);
System.out.println("List 2: " + list2);
System.out.println("Is List 2 contained in List 1: " + CollectionUtils.isSubCollection(list2, list1));
}
}
Apache Commons Collections - Intersection
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.
Checking intersection
CollectionUtils 的 intersection() 方法可用于获取两个集合之间的公共对象(交集)。
intersection() method of CollectionUtils can be used to get the common objects between two collections(intersection).
Declaration
以下是 org.apache.commons.collections4.CollectionUtils.intersection() 方法的声明 -
Following is the declaration for org.apache.commons.collections4.CollectionUtils.intersection() method −
public static <O> Collection<O> intersection(Iterable<? extends O> a, Iterable<? extends O> b)
Parameters
-
a − The first (sub) collection, must not be null.
-
b − The second (super) collection, must not be null.
Example
以下示例展示了 org.apache.commons.collections4.CollectionUtils.intersection() 方法的用法。我们将获取两个列表的交集。
The following example shows the usage of org.apache.commons.collections4.CollectionUtils.intersection() method. We’ll get the intersection of two lists.
import java.util.Arrays;
import java.util.List;
import org.apache.commons.collections4.CollectionUtils;
public class CollectionUtilsTester {
public static void main(String[] args) {
//checking inclusion
List<String> list1 = Arrays.asList("A","A","A","C","B","B");
List<String> list2 = Arrays.asList("A","A","B","B");
System.out.println("List 1: " + list1);
System.out.println("List 2: " + list2);
System.out.println("Commons Objects of List 1 and List 2: " + CollectionUtils.intersection(list1, list2));
}
}
Apache Commons Collections - Subtraction
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.
Checking Substraction
CollectionUtils 的 subtract() 方法可用于获取新集合,方法是从其他集合中减去一个集合的对象。
subtract() method of CollectionUtils can be used to get the new collection by subtracting objects of one collection from other.
Declaration
以下是 org.apache.commons.collections4.CollectionUtils.subtract() 方法的声明:
Following is the declaration for org.apache.commons.collections4.CollectionUtils.subtract() method −
public static <O> Collection<O> subtract(Iterable<? extends O> a, Iterable<? extends O> b)
Parameters
-
a − The collection to subtract from, must not be null.
-
b − The collection to subtract, must not be null.
Example
以下示例展示了 org.apache.commons.collections4.CollectionUtils.subtract() 方法的用法。我们将得到两个列表相减的结果。
The following example shows the usage of org.apache.commons.collections4.CollectionUtils.subtract() method. We’ll get the subtraction of two lists.
import java.util.Arrays;
import java.util.List;
import org.apache.commons.collections4.CollectionUtils;
public class CollectionUtilsTester {
public static void main(String[] args) {
//checking inclusion
List<String> list1 = Arrays.asList("A","A","A","C","B","B");
List<String> list2 = Arrays.asList("A","A","B","B");
System.out.println("List 1: " + list1);
System.out.println("List 2: " + list2);
System.out.println("List 1 - List 2: "+ CollectionUtils.subtract(list1, list2));
}
}
Apache Commons Collections - Union
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.
Checking union
CollectionUtils 的 union() 方法可用于获取两个集合的并集。
union() method of CollectionUtils can be used to get the union of two collections.
Declaration
以下是 org.apache.commons.collections4.CollectionUtils.union() 方法的声明 -
Following is the declaration for org.apache.commons.collections4.CollectionUtils.union() method −
public static <O> Collection<O> union(Iterable<? extends O> a, Iterable<? extends O> b)
Example
以下示例显示了 org.apache.commons.collections4.CollectionUtils.union() 方法的用法。我们将获得两个列表的并集。
The following example shows the usage of org.apache.commons.collections4.CollectionUtils.union() method. We’ll get the union of two lists.
import java.util.Arrays;
import java.util.List;
import org.apache.commons.collections4.CollectionUtils;
public class CollectionUtilsTester {
public static void main(String[] args) {
//checking inclusion
List<String> list1 = Arrays.asList("A","A","A","C","B","B");
List<String> list2 = Arrays.asList("A","A","B","B");
System.out.println("List 1: " + list1);
System.out.println("List 2: " + list2);
System.out.println("Union of List 1 and List 2: "+ CollectionUtils.union(list1, list2));
}
}