
Commons Collection Interfaces
- Commons Collections - Bag Interface
- Commons Collections - BidiMap Interface
- Commons Collections - MapIterator Interface
- Commons Collections - OrderedMap Interface
Commons Collections Usage
- Commons Collections - Ignore Null
- Commons Collections - Merge & Sort
- Commons Collections - Transforming Objects
- Commons Collections - Filtering Objects
- Commons Collections - Safe Empty Checks
- Commons Collections - Inclusion
- Commons Collections - Intersection
- Commons Collections - Subtraction
- Commons Collections - Union
Commons Collections Resource
Apache Commons Collections - Subtraction
Checking subtraction
subtract() method of CollectionUtils can be used to get the new collection by subtracting objects of one collection from other.
Usage
List list3 = CollectionUtils.subtract(list1, list2);
Declaration
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 first collection, must not be null.
b − The second collection, must not be null.
Return Value
The subtraction of the two collections.
Example - Getting subtraction of Two Lists with some common elements
The following example shows the usage of subtract() method. We'll get the subtraction of two lists.
CommonCollectionsTester.java
package com.tutorialspoint; import java.util.Arrays; import java.util.List; import org.apache.commons.collections4.CollectionUtils; public class CommonCollectionsTester { 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)); } }
Output
When you run the code, you will see the following output −
List 1: [A, A, A, C, B, B] List 2: [A, A, B, B] List 1 - List 2: [A, C]
Example - Getting subtraction of Two Lists with no common elements
The following example shows the usage of subtract() method. We'll get the subtraction of two lists.
CommonCollectionsTester.java
package com.tutorialspoint; import java.util.Arrays; import java.util.List; import org.apache.commons.collections4.CollectionUtils; public class CommonCollectionsTester { public static void main(String[] args) { //checking inclusion List<String> list1 = Arrays.asList("A","A","A","C","B","B"); List<String> list2 = Arrays.asList("D","E","F","F"); System.out.println("List 1: " + list1); System.out.println("List 2: " + list2); System.out.println("List 1 - List 2: " + CollectionUtils.subtract(list1, list2)); } }
Output
When you run the code, you will see the following output −
List 1: [A, A, A, C, B, B] List 2: [D, E, F, F] List 1 - List 2: [A, A, A, C, B, B]
Advertisements