Commons Collections – Ignore Null

Apache Commons Collections – Ignore Null ”; Previous Next 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. 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 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”); } } } Output The output is mentioned below − [a] Null value is not present Print Page Previous Next Advertisements ”;

Commons Collections – Transforming Objects

Commons Collections – Transforming Objects ”; Previous Next 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 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() 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 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); } } Output When you use the code, you will get the following code − [1, 2, 3] Print Page Previous Next Advertisements ”;

Commons Collections – Quick Guide

Apache Commons Collections – Quick Guide ”; Previous Next 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. 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 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 is freely available from the link www.oracle.com/technetwork/java/archive-139210.html So, you download a version based on your operating system. 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 We are assuming that you have installed Java in c:Program Filesjavajdk 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:WINDOWSSYSTEM32”, then change your path to read ”C:WINDOWSSYSTEM32;c:Program Filesjavajdkbin”. Setting up the Path for Windows 95/98/ME We are assuming that you have installed Java in c:Program Filesjavajdk directory. Edit the ”C:autoexec.bat” file and add the following line at the end − ”SET PATH=%PATH%;C:Program Filesjavajdkbin”. Setting up the Path for Linux, UNIX, Solaris, FreeBSD 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. 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 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 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 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 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 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 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

Commons Collections – Environment Setup

Commons Collections – Environment Setup ”; Previous Next Local Environment Setup 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 is freely available from the link www.oracle.com/technetwork/java/archive-139210.html So, you download a version based on your operating system. 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 We are assuming that you have installed Java in c:Program Filesjavajdk 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:WINDOWSSYSTEM32”, then change your path to read ”C:WINDOWSSYSTEM32;c:Program Filesjavajdkbin”. Setting up the Path for Windows 95/98/ME We are assuming that you have installed Java in c:Program Filesjavajdk directory. Edit the ”C:autoexec.bat” file and add the following line at the end − ”SET PATH=%PATH%;C:Program Filesjavajdkbin”. Setting up the Path for Linux, UNIX, Solaris, FreeBSD 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. 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 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 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 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 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:. Print Page Previous Next Advertisements ”;

Commons Collections – OrderedMap Interface

Commons Collections – OrderedMap Interface ”; Previous Next 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 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”)); } } Output The result will be as follows − One Two Three Print Page Previous Next Advertisements ”;

Commons Collections – BidiMap Interface

Commons Collections – BidiMap Interface ”; Previous Next 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 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.Ge. org.apache.commons.collections4.IterableGe. org.apache.commons.collections4.Pu. java.util.Ma. Example of BidiMap Interface 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); } } 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} Print Page Previous Next Advertisements ”;

Commons Collections – Intersection

Apache Commons Collections – Intersection ”; Previous Next 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 intersection() method of CollectionUtils can be used to get the common objects between two collections(intersection). 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 (sub) collection, must not be null. b − The second (super) collection, must not be null. Return Value The intersection of the two collections. Example 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)); } } 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] Print Page Previous Next Advertisements ”;

Commons Collections – Merge & Sort

Apache Commons Collections – Merge & Sort ”; Previous Next 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 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() 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 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); } } Output The output is as follows − [A, B, C, D, E, F] Print Page Previous Next Advertisements ”;

Commons Collections – MapIterator Interface

Commons Collections – MapIterator Interface ”; Previous Next 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 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); } } 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 {3=Three_, 5=Five_, 2=Two_, 4=Four_, 1=One_} Print Page Previous Next Advertisements ”;