- Commons Collections - Discussion
- Commons Collections - Useful Resources
- Commons Collections - Quick Guide
- Commons Collections - Union
- Commons Collections - Subtraction
- Commons Collections - Intersection
- Commons Collections - Inclusion
- Commons Collections - Safe Empty Checks
- Commons Collections - Filtering Objects
- Commons Collections - Transforming Objects
- Commons Collections - Merge & Sort
- Commons Collections - Ignore Null
- Commons Collections - OrderedMap Interface
- Commons Collections - MapIterator Interface
- Commons Collections - BidiMap Interface
- Commons Collections - Bag Interface
- Commons Collections - Environment Setup
- Commons Collections - Overview
- Commons Collections - Home
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Apache Commons Collections - Subtraction
CollectionUtils class of Apache Commons Collections pbrary provides various utipty methods for common operations covering wide range of use cases. It helps avoid writing boilerplate code. This pbrary is very useful prior to jdk 8 as similar functionapties are now provided in Java 8 s Stream API.
Checking Substraction
subtract() method of CollectionUtils can be used to get the new collection by subtracting objects of one collection from other.
Declaration
Following is the declaration for org.apache.commons.collections4.CollectionUtils.subtract() method −
pubpc 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.
Return Value
A new collection with the results.
Example
The following example shows the usage of org.apache.commons.collections4.CollectionUtils.subtract() method. We ll get the subtraction of two psts.
import java.util.Arrays; import java.util.List; import org.apache.commons.collections4.CollectionUtils; pubpc class CollectionUtilsTester { pubpc static void main(String[] args) { //checking inclusion List<String> pst1 = Arrays.asList("A","A","A","C","B","B"); List<String> pst2 = Arrays.asList("A","A","B","B"); System.out.println("List 1: " + pst1); System.out.println("List 2: " + pst2); System.out.println("List 1 - List 2: "+ CollectionUtils.subtract(pst1, pst2)); } }
Output
When you execute the above code, you should see the following output −
List 1: [A, A, A, C, B, B] List 2: [A, A, B, B] List 1 - List 2: [A, C]Advertisements