Apache Commons Collections - Quick Guide



Apache Commons Collections - Overview

Commons Collections augments Java Collections Framework. It provides several features to make collection handling easy. It provides many new interfaces, implementations and utilities.

Features of Common Collections

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.

Apache Commons Collections - Environment Setup

This chapter will guide you on how to prepare a development environment to start your work with Apache Commons Collections. It will also teach you how to set up JDK on your machine before you set up Apache Commons Collections −

Setup Java Development Kit (JDK)

You can download the latest version of SDK from Oracle's Java site − Java SE Downloads. You will find instructions for installing JDK in downloaded files, follow the given instructions to install and configure the setup. Finally set PATH and JAVA_HOME environment variables to refer to the directory that contains java and javac, typically java_install_dir/bin and java_install_dir respectively.

If you are running Windows and have installed the JDK in C:\jdk-19, you would have to put the following line in your C:\autoexec.bat file.

set PATH=C:\jdk-19;%PATH% 
set JAVA_HOME=C:\jdk-19

Alternatively, on Windows NT/2000/XP, you will have to right-click on My Computer, select Properties → Advanced → Environment Variables. Then, you will have to update the PATH value and click the OK button.

On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk-19 and you use the C shell, you will have to put the following into your .cshrc file.

setenv PATH /usr/local/jdk-19/bin:$PATH 
setenv JAVA_HOME /usr/local/jdk-19

Alternatively, if you use an Integrated Development Environment (IDE) like Borland JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, you will have to compile and run a simple program to confirm that the IDE knows where you have installed Java. Otherwise, you will have to carry out a proper setup as given in the document of the IDE.

Popular Java Editors

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

Download the latest version of Apache Common Collections jar file from Download Apache Commons Collections Page. At the time of writing this tutorial, we have downloaded commons-collections4-4.5.0-bin.zip and copied it into C:\>Apache folder.

OS Archive name
Windows commons-collections4-4.5.0-bin.zip
Linux commons-collections4-4.5.0-bin.tar.gz
Mac commons-collections4-4.5.0-bin.tar.gz

Set Apache Common Collections Environment

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.5.0-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

Set the CLASSPATH environment variable to point to the Common Collections jar location. Assuming, you have stored commons-collections4-4.5.0-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.5.0-bin.jar;.;
Linux export CLASSPATH=$CLASSPATH:$APACHE_HOME/commons-collections4-4.5.0-bin.jar:.
Mac export CLASSPATH=$CLASSPATH:$APACHE_HOME/commons-collections4-4.5.0-bin.jar:.

Apache Commons Collections - Bag Interface

Overview

A Bag interface 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

Following is the declaration for org.apache.commons.collections4.Bag<E> interface −

public interface Bag<E>
   extends Collection<E>

Methods

The methods for Bag Interface 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.Collection.

Example - Adding elements to the Bag

CommonCollectionsTester.java

package com.tutorialspoint;

import org.apache.commons.collections4.Bag;
import org.apache.commons.collections4.bag.HashBag;

public class CommonCollectionsTester {
   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);
   }
}

Output

You will see the following output −

d is present 3 times.
bag: [2:a,1:b,1:c,3:d]

Example - Getting Unique Set from the Bag

CommonCollectionsTester.java

package com.tutorialspoint;

import org.apache.commons.collections4.Bag;
import org.apache.commons.collections4.bag.HashBag;

public class CommonCollectionsTester {
   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 set of unique values from the bag
      System.out.println("Unique Set: " +bag.uniqueSet());
   }
}

Output

You will see the following output −

Unique Set: [a, b, c, d]

Example - Removing Occurences of an Element from the Bag

CommonCollectionsTester.java

package com.tutorialspoint;

import org.apache.commons.collections4.Bag;
import org.apache.commons.collections4.bag.HashBag;

public class CommonCollectionsTester {
   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);
      
      //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());
   }
}

Output

You will see the following output −

2 occurences of d removed from bag: [2:a,1:b,1:c,1:d]
d is present 1 times.
bag: [2:a,1:b,1:c,1:d]
Unique Set: [a, b, c, d]

Apache Commons Collections - BidiMap Interface

Overview

BidiMap Interface represents a bidirectional Map. Using bidirectional map, a key can be lookup using value and value can be lookup using key easily.

Interface Declaration

Following is the declaration for org.apache.commons.collections4.BidiMap<K,V> interface −

public interface BidiMap<K,V>
   extends IterableMap<K,V>

Methods

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.Get.

  • org.apache.commons.collections4.IterableGet.

  • org.apache.commons.collections4.Put.

  • java.util.Map.

Example - Adding Elements to a BidiMap

CommonCollectionsTester.java

package com.tutorialspoint;

import org.apache.commons.collections4.BidiMap;
import org.apache.commons.collections4.bidimap.TreeBidiMap;

public class CommonCollectionsTester {
   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);
   }
}

Output

When you run the code, you will see the following output −

1
One
Original Map: {One=1, Three=3, Two=2}

Example - Removing Element from a BidiMap

CommonCollectionsTester.java

package com.tutorialspoint;

import org.apache.commons.collections4.BidiMap;
import org.apache.commons.collections4.bidimap.TreeBidiMap;

public class CommonCollectionsTester {
   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("Original Map: " + bidi);      
      bidi.removeValue("1");
      System.out.println("Modified Map: " + bidi);
   }
}

Output

When you run the code, you will see the following output −

Original Map: {One=1, Three=3, Two=2}
Modified Map: {Three=3, Two=2}

Example - Inverse a BidiMap

CommonCollectionsTester.java

package com.tutorialspoint;

import org.apache.commons.collections4.BidiMap;
import org.apache.commons.collections4.bidimap.TreeBidiMap;

public class CommonCollectionsTester {
   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("Original Map: " + bidi);
      BidiMap<String, String> inversedMap = bidi.inverseBidiMap();
      System.out.println("Inversed Map: " + inversedMap);
   }
}

Output

When you run the code, you will see the following output −

1
One
Original Map: {One=1, Three=3, Two=2}
Modified Map: {Three=3, Two=2}
Inversed Map: {2=Two, 3=Three}

Apache Commons Collections - MapIterator Interface

Overview

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.

Interface Declaration

Following is the declaration for org.apache.commons.collections4.MapIterator<K,V> interface −

public interface MapIterator<K,V>
   extends Iterator<K>

Methods

The methods for MapIterator interface are as follows −

Sr.No. Method & Description
1

K getKey()

Gets the current key, which is the key returned by the last call to next().

2

V getValue()

Gets the current value, which is the value associated with the last key returned by next().

3

boolean hasNext()

Checks to see if there are more entries still to be iterated.

4

K next()

Gets the next key from the Map.

5

void remove()

Removes the last returned key from the underlying Map (optional operation).

6

V setValue(V value)

Sets the value associated with the current key (optional operation).

Methods Inherited

This interface inherits methods from the following interface −

  • java.util.Iterator.

Example - Printing key-value pairs using MapIterator Interface

CommonCollectionsTester.java

package com.tutorialspoint;

import org.apache.commons.collections4.IterableMap;
import org.apache.commons.collections4.MapIterator;
import org.apache.commons.collections4.map.HashedMap;

public class CommonCollectionsTester {
   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);
      }
   }
}

Output

The output is stated below −

key: 3
Value: Three
key: 5
Value: Five
key: 2
Value: Two
key: 4
Value: Four
key: 1
Value: One

Example - Modifying value during iteration using MapIterator Interface

CommonCollectionsTester.java

package com.tutorialspoint;

import org.apache.commons.collections4.IterableMap;
import org.apache.commons.collections4.MapIterator;
import org.apache.commons.collections4.map.HashedMap;

public class CommonCollectionsTester {
   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();
         iterator.setValue(value + "_");
      }
      System.out.println(map);
   }
}

Output

The output is stated below −

{3=Three_, 5=Five_, 2=Two_, 4=Four_, 1=One_}

Example - Removing value during iteration using MapIterator Interface

CommonCollectionsTester.java

package com.tutorialspoint;

import org.apache.commons.collections4.IterableMap;
import org.apache.commons.collections4.MapIterator;
import org.apache.commons.collections4.map.HashedMap;

public class CommonCollectionsTester {
   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();
         if(key == "1"){
            iterator.remove();
         }
      }
      System.out.println(map);
   }
}

Output

The output is stated below −

{3=Three, 5=Five, 2=Two, 4=Four} 

Apache Commons Collections - OrderedMap Interface

Overview

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.

Interface Declaration

Following is the declaration for org.apache.commons.collections4.OrderedMap<K,V> interface −

public interface OrderedMap<K,V>
   extends IterableMap<K,V>

Methods

The methods for OrderedMap Interface are as follows −

Sr.No. Method & Description
1

K firstKey()

Gets the first key currently in this map.

2

K lastKey()

Gets the last key currently in this map.

3

OrderedMapIterator<K,V> mapIterator()

Obtains an OrderedMapIterator over the map.

4

K nextKey(K key)

Gets the next key after the one specified.

5

K previousKey(K key)

Gets the previous key before the one specified.

Methods Inherited

This interface inherits methods from the following interface −

  • org.apache.commons.collections4.Get
  • java.util.Map.

Example - Printing First and Last Keys using OrderedMap Interface

CommonCollectionsTester.java

package com.tutorialspoint;

import org.apache.commons.collections4.OrderedMap;
import org.apache.commons.collections4.map.LinkedMap;

public class CommonCollectionsTester {
   public static void main(String[] args) {
      OrderedMap<String, String> map = new LinkedMap<>();
      map.put("One", "1");
      map.put("Two", "2");
      map.put("Three", "3");
      
      System.out.println(map.firstKey());
	  System.out.println(map.lastKey());
   }
}

Output

The output is stated below −

One
Three

Example - Iterating an OrderedMap

CommonCollectionsTester.java

package com.tutorialspoint;

import org.apache.commons.collections4.MapIterator;
import org.apache.commons.collections4.OrderedMap;
import org.apache.commons.collections4.map.LinkedMap;

public class CommonCollectionsTester {
   public static void main(String[] args) {
      OrderedMap<String, String> map = new LinkedMap<>();
      map.put("One", "1");
      map.put("Two", "2");
      map.put("Three", "3");
      
      MapIterator<String, String> iterator = map.mapIterator();
      while (iterator.hasNext()) {
         Object key = iterator.next();
         Object value = iterator.getValue();
         System.out.println("Key: " + key, ", Value: " + value);
      }
   }
}

Output

The output is stated below −

Key: One, Value: 1
Key: Two, Value: 2
Key: Three, Value: 3

Example - Getting Previous/Next keys from an OrderedMap

CommonCollectionsTester.java

package com.tutorialspoint;

import org.apache.commons.collections4.OrderedMap;
import org.apache.commons.collections4.map.LinkedMap;

public class CommonCollectionsTester {
   public static void main(String[] args) {
      OrderedMap<String, String> map = new LinkedMap<>();
      map.put("One", "1");
      map.put("Two", "2");
      map.put("Three", "3");
      
      System.out.println(map.previousKey("Two"));
	  System.out.println(map.nextKey("Two"));
   }
}

Output

The output is stated below −

One
Three

Apache Commons Collections - ResettableIterator Interface

Overview

ResettableIterator provides a simple iterator which can be reset back to its initial state. It makes iterator to be reused repeatedly.

Interface Declaration

Following is the declaration for org.apache.commons.collections4.ResettableIterator<E> interface −

public interface ResettableIterator<E>
   extends Iterator<E>

Methods

The methods for ResettableIterator Interface are as follows −

Sr.No. Method & Description
1

void reset()

Resets the iterator back to the position at which the iterator was created.

Methods Inherited

This interface inherits methods from the following interface −

  • java.util.Iterator.

Example - Resetting Iterator on Arrays and Reusing it

CommonCollectionsTester.java

package com.tutorialspoint;

import org.apache.commons.collections4.iterators.ArrayIterator;

public class CommonCollectionsTester {
   public static void main(String[] args) {

      String[] values = {"A", "B", "C", "D", "E"};
      ArrayIterator<String> iterator = new ArrayIterator<>(values);

      // iterate and print all values
      while (iterator.hasNext()) {
         System.out.print(iterator.next() + " ");
      } 

      // Reset the iterator
      iterator.reset();
      System.out.println();

      // iterate and print all values again using same iterator
      while (iterator.hasNext()) {
         System.out.print(iterator.next() + " ");
      } 
   }
}

Output

The output is stated below −

A B C D E 
A B C D E

Example - Resetting Iterator on List and Reusing it

CommonCollectionsTester.java

package com.tutorialspoint;

import java.util.Arrays;
import java.util.List;

import org.apache.commons.collections4.iterators.ListIteratorWrapper;

public class CommonCollectionsTester {
   public static void main(String[] args) {
	   
	   List<String> values = Arrays.asList("A", "B", "C", "D", "E");
	   ListIteratorWrapper<String> iterator = new ListIteratorWrapper<>(values.iterator());
       
       // iterate and print all values
       while (iterator.hasNext()) {
           System.out.print(iterator.next() + " ");
       } 

       // Reset the iterator
       iterator.reset();
       System.out.println();

       // iterate and print all values again using same iterator
       while (iterator.hasNext()) {
           System.out.print(iterator.next() + " ");
       } 
	   
   }
}

Output

The output is stated below −

A B C D E 
A B C D E

Apache Commons Collections - Ignore Null

Overview

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

addIgnoreNull() method of CollectionUtils can be used to ensure that only non-null values are getting added to the collection.

Usage

a = "a";
b = null;
CollectionUtils.addIgnoreNull(list, a);
CollectionUtils.addIgnoreNull(list, b); // b being null will not be added.

Declaration

Following is the declaration for

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.

Return Value

True if the collection changed.

Exception

  • NullPointerException − If the collection is null.

Example - Usage of addIgnoreNull() method to ignore null values

The following example shows the usage of addIgnoreNull() method. We are trying to add a null value and a sample non-null value.

CommonCollectionsTester.java

package com.tutorialspoint;

import java.util.LinkedList;
import java.util.List;
import org.apache.commons.collections4.CollectionUtils;

public class CommonCollectionsTester {
   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");
      }
   }
}

Output

The output is mentioned below −

[a]
Null value is not present

Apache Commons Collections - Merging Sorted Data

Merging two sorted lists

Syntax

collate() method of CollectionUtils can be used to merge two already sorted lists.

List<String> mergedList = CollectionUtils.collate(sortedList1, sortedList2);

Declaration

Following is the declaration for

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)

Parameters

  • a − The first collection, must not be null.

  • b − The second collection, must not be null.

Return Value

A new sorted List, containing the elements of Collection a and b.

Exception

  • NullPointerException − If either collection is null.

Example - Merging two sorted Lists

The following example shows the usage of collate() method. We'll merge two sorted lists and then print the merged and sorted list.

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) {
      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);
   }
}

Output

The output is as follows −

[A, B, C, D, E, F]

Apache Commons Collections - Transforming Objects

Transforming a list of objects

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

Usage

List<Integer> integerList = (List<Integer>) CollectionUtils.collect(stringList,
   new Transformer<String, Integer>() {
      @Override
      public Integer transform(String input) {
         return Integer.parseInt(input);
      }
});

Declaration

Following is the declaration for

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.

Return Value

The transformed result (new list).

Exception

  • NullPointerException − If the input collection is null.

Example - Transforming a List of String to List of Integers

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.

CommonCollectionsTester.java

package com.tutorialspoint;

import java.util.Arrays;
import java.util.List;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.Transformer;

public class CommonCollectionsTester {
   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]

Apache Commons Collections - Filtering Objects

Filtering a list

filter() method of CollectionUtils can be used to filter a list to remove objects which do not satisfy condition provided by predicate passed.

Usage

CollectionUtils.filter(integerList, new Predicate<Integer>() {
   @Override
   public boolean evaluate(Integer input) {
      if(input.intValue() % 2 == 0) {
         return true;
      }
      return false;
   }
});

Declaration

Following is the declaration for

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 if the collection is modified by this call, false otherwise.

Example - Filtering out odd numbers from a List of integers

The following example shows the usage of filter() method. We'll filter a list of integer to get even numbers only.

CommonCollectionsTester.java

package com.tutorialspoint;

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 CommonCollectionsTester {
   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);
   }
}

Output

It will produce the following result −

Original List: [1, 2, 3, 4, 5, 6, 7, 8]
Filtered List (Even numbers): [2, 4, 6, 8]

filterInverse() method

filterInverse() method of CollectionUtils can be used to filter a list to remove objects, which satisfy condition provided by predicate passed.

Usage

CollectionUtils.filterInverse(integerList, new Predicate<Integer>() {
   @Override
   public boolean evaluate(Integer input) {
      if(input.intValue() % 2 == 0) {
         return true;
      }
      return false;
   }
});

Declaration

Following is the declaration for

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 if the collection is modified by this call, false otherwise.

Example - Filtering out even numbers from a List of integers

The following example shows the usage of filterInverse() method. We'll filter a list of integer to get odd numbers only.

CommonCollectionsTester.java

package com.tutorialspoint;

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 CommonCollectionsTester {
   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);
   }
}

Output

The result is as stated below −

Original List: [1, 2, 3, 4, 5, 6, 7, 8]
Filtered List (Odd numbers): [1, 3, 5, 7]

Apache Commons Collections - Safe Empty Checks

Checking non-empty list

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.

Usage

CollectionUtils.isNotEmpty(list)

Declaration

Following is the declaration for

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

public static boolean isNotEmpty(Collection<?> coll)

Parameters

  • coll − The collection to check, may be null.

Return Value

True if non-null and non-empty.

Example - Checking a List to be non-empty in Safer way

The following example shows the usage of org.apache.commons.collections4.CollectionUtils.isNotEmpty() method. We'll check a list is empty or not.

CommonCollectionsTester.java

package com.tutorialspoint;

import java.util.List;
import org.apache.commons.collections4.CollectionUtils;

public class CommonCollectionsTester {
   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);
   }
}

Output

The output is given below −

Non-Empty List Check: false
Non-Empty List Check: false

Checking a List to be empty in Safer way

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.

Usage

CollectionUtils.isEmpty(list);

Declaration

Following is the declaration for

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

public static boolean isEmpty(Collection<?> coll)

Parameters

  • coll − The collection to check, may be null.

Return Value

True if empty or null.

Example - Checking a List to be empty

The following example shows the usage of org.apache.commons.collections4.CollectionUtils.isEmpty() method. We'll check a list is empty or not.

CommonCollectionsTester.java

package com.tutorialspoint;

import java.util.List;
import org.apache.commons.collections4.CollectionUtils;

public class CommonCollectionsTester {
   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);
   }
}

Output

Given below is the output of the code −

Empty List Check: true
Empty List Check: true

Apache Commons Collections - Inclusion

Checking sublist

isSubCollection() method of CollectionUtils can be used to check if a collection contains the given collection or not.

Usage

// check if list2 is contained in list1
boolean result = CollectionUtils.isSubCollection(list2, list1);

Declaration

Following is the declaration for

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.

Return Value

True if and only if a is a sub-collection of b.

Example - Checking if List contains a sublist

The following example shows the usage of isSubCollection() method. We'll check a list is part of another list or not.

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("Is List 2 contained in List 1: " + CollectionUtils.isSubCollection(list2, list1));
   }
}

Output

You will receive the following output −

List 1: [A, A, A, C, B, B]
List 2: [A, A, B, B]
Is List 2 contained in List 1: true

Example - Checking if List is not containing a sublist

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.

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","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));
   }
}

Output

You will receive the following output −

List 1: [A, A, A, C, B, B]
List 2: [A, A, B, B, B]
Is List 2 contained in List 1: false

Apache Commons Collections - Intersection

Checking intersection

intersection() method of CollectionUtils can be used to get the common objects between two collections(intersection).

Usage

List list3 = CollectionUtils.intersection(list1, list2);

Declaration

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 collection, must not be null.

  • b − The second collection, must not be null.

Return Value

The intersection of the two collections.

Example - Getting Intersection of Two Lists with some common elements

The following example shows the usage of intersection() method. We'll get the intersection 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("Commons Objects of List 1 and List 2: " + CollectionUtils.intersection(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]
Commons Objects of List 1 and List 2: [A, A, B, B]

Example - Getting Intersection of Two Lists with no common elements

The following example shows the usage of intersection() method. We'll get the intersection 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("Commons Objects of List 1 and List 2: " + CollectionUtils.intersection(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]
Commons Objects of List 1 and List 2: []

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]

Apache Commons Collections - Union

Checking union

union() method of CollectionUtils can be used to get the union between two collections.

Usage

List list3 = CollectionUtils.union(list1, list2);

Declaration

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)

Parameters

  • a − The first collection, must not be null.

  • b − The second collection, must not be null.

Return Value

The union of the two collections.

Example - Getting Union of Two Lists with some common elements

The following example shows the usage of union() method. We'll get the union 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("Union of List 1 and List 2: " + CollectionUtils.union(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]
Union of List 1 and List 2: [A, A, A, B, B, C]

Example - Getting Union of Two Lists with no common elements

The following example shows the usage of union() method. We'll get the union 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("Union of List 1 and List 2: " + CollectionUtils.union(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]
Union of List 1 and List 2: [A, A, A, B, B, C, D, E, F, F]
Advertisements