CodeGym /Java Course /Module 3. Java Professional /CollectionUtils class from Apache Commons

CollectionUtils class from Apache Commons

Module 3. Java Professional
Level 20 , Lesson 4
Available

Introduction to CollectionUtils

Another generic utility class that contains many useful methods:

addAll(Collection<C> collection, C...elements) Adds all elements of array C to the collection
addIgnoreNull(Collection<T> collection, T object) Adds an element if it is not null
containsAll(Collection<?> coll1, Collection<?> coll2) Checks that collection1 contains all elements of collection2
containsAny(Collection<?> coll1, Collection<?> coll2) Checks that collection1 contains at least one element from collection2
countMatches(Iterable<C> input, Predicate<? super C> predicate) Counts how many elements in a collection satisfy a predicate rule
disjunction(Iterable<? extends O> a, Iterable<? extends O> b) Returns objects that are in only one collection, but not both
intersection(Iterable<? extends O> a, Iterable<? extends O> b) Returns a collection of objects that are part of both collections at once
union(Iterable<? extends O> a, Iterable<? extends O> b) Returns a collection of objects that are part of at least one collection
emptyCollection() Returns a special empty collection
emptyIfNull(Collection<T> collection) Returns an empty collection if collection == null
exists(Iterable<C> input, Predicate<? super C> predicate) Checks if there is an element in the collection that satisfies the predicate rule
extractSingleton(Collection<E> collection) Returns the only element of the collection
filter(Iterable<T> collection, Predicate<? super T> predicate) Filters the elements of a collection
find(Iterable<T> collection, Predicate<? super T> predicate) Looking for elements of a collection
isEmpty(Collection<?> coll) Checks if the collection is empty
isEqualCollection(Collection<?> a, Collection<?> b) Compares collections
isFull(Collection<? extends Object> coll) Checks if an element can still be added to the collection
isNotEmpty(Collection<?> coll) Check if the collection is not empty
isSubCollection(Collection<?> a, Collection<?> b) Checks if collection B is in collection A
matchesAll(Iterable<C> input, Predicate<? super C> predicate) Checks that all elements of a collection satisfy a predicate rule
removeAll(Collection<E> collection, Collection<?> remove) Removes all elements of the collection
retainAll(Collection<C> collection, Collection<?> retain) Returns a collection containing all elements of collection that are also contained in retain
reverseArray(Object[] array) Reverses an array backwards
unmodifiableCollection(Collection<? extends C> collection) Returns a wrapper over the collection. Any attempt to modify the collection will throw an exception.

Let's look at some methods.

Ways to check if a collection is empty

Here's how easy it is to determine if a collection is empty:

CollectionUtils.isEmpty(null); // true
CollectionUtils.isEmpty(new LinkedList<>()); // true
CollectionUtils.isEmpty(Collections.singleton(new int[]{2, 1})); // false

It's just as easy to check that a collection is not empty:

CollectionUtils.isNotEmpty(null); // false
CollectionUtils.isNotEmpty(new LinkedList<>()); // false
CollectionUtils.isNotEmpty(Collections.singleton(new int[]{2, 1})); // true

Examples:

User ivan = new User("Ivan", "ivan@email.com");
User petr = new User("Petr", "petr@email.com");

List<User> users = new ArrayList<>();

System.out.println(CollectionUtils.isEmpty(users)); // true
System.out.println(CollectionUtils.isNotEmpty(users)); // false

users.add(ivan);
users.add(petr);

System.out.println(CollectionUtils.isEmpty(users)); // false
System.out.println(CollectionUtils.isNotEmpty(users)); // true

users = null;
System.out.println(CollectionUtils.isEmpty(users)); // true
System.out.println(CollectionUtils.isNotEmpty(users)); // false

A Guide to Apache Commons Collections CollectionUtils

Operations on sets

If you had to deal with set theory, then you know that there are 4 basic operations on sets: union, intersection, difference and disjunction.

For these operations, the CollectionUtils class has 4 methods:

  • union()
  • intersection()
  • disjunction()
  • subtract()

Below are some simple examples:

An association

List<String> firstList = Arrays.asList("1", "2", "3", "4", "5", "6");
List<String> secondList = Arrays.asList("2", "3", "6", "7", "8", "9");

//combine two sets
Collection<String> result = CollectionUtils.union(firstList, secondList);
System.out.println(ArrayUtils.toString(result));     //[1, 2, 3, 4, 5, 6, 7, 8, 9]

intersection

List<String> firstList = Arrays.asList("A", "B", "C", "D", "E", "F");
List<String> secondList = Arrays.asList("B", "D", "F", "G", "H", "K");

//intersections of two sets
Collection<String> result = CollectionUtils.intersection(firstList, secondList);
System.out.println(ArrayUtils.toString(result));     //[B, D, F]

Disjunction

List<String> firstList = Arrays.asList("1", "2", "3", "4", "5", "6");
List<String> secondList = Arrays.asList("2", "3", "6", "7", "8", "9");

//disjunction
Collection<String> result = CollectionUtils.disjunction(firstList, secondList);
System.out.println(ArrayUtils.toString(result)); //[1, 4, 5, 7, 8, 9]

Difference (deduction)

List<String> firstList = Arrays.asList("1", "2", "3", "4", "5", "6");
List<String> secondList = Arrays.asList("2", "3", "6", "7", "8", "9");

//difference
Collection<String> result = CollectionUtils.subtract(firstList, secondList);
System.out.println(ArrayUtils.toString(result)); // [1, 4, 5]

Operations on sets, continued

This example shows how to use the above four methods to work with two collections:

List<Integer> firstList = Arrays.asList(1, 2, 3, 3, 4, 5);
List<Integer> secondList = Arrays.asList(3, 4, 4, 5, 6, 7);

Collection<Integer> union = CollectionUtils.union(firstList, secondList); // An association
Collection<Integer> intersection = CollectionUtils.intersection(firstList, secondList); // Intersection
Collection<Integer> disjunction = CollectionUtils.disjunction(firstList, secondList); // disjunction
Collection<Integer> subtract = CollectionUtils.subtract(firstList, secondList); // Difference

System.out.println("firstList: " + ArrayUtils.toString(firstList.toArray()));
System.out.println("secondList: " + ArrayUtils.toString(secondList.toArray()));

System.out.println("An association: " + ArrayUtils.toString(union.toArray()));
System.out.println("Intersection: " + ArrayUtils.toString(intersection.toArray()));
System.out.println("Disjunction: " + ArrayUtils.toString(disjunction.toArray()));
System.out.println("Difference: " + ArrayUtils.toString(subtract.toArray()));

Our result:

firstList: {1,2,3,3,4,5}
secondList: {3,4,4,5,6,7}
An association: {1,2,3,3,4,4,5,6,7}
intersection: {3,4,5}
Disjunction: {1,2,3,4,6,7}
Difference: {1,2,3}

You can experiment with these methods on your own.

unmodifiableCollection() Method

Sometimes we need to implement interface methods that need to return collections of our objects' internal data. And since the data is internal, we don't want anyone to change it somewhere.

Or we have received somewhere a collection that does not need to be changed, but is forced to pass it to some third-party method. Where is the guarantee that he will not change it?

In order to sleep peacefully, the collection can be wrapped in a special wrapper that will throw an exception when trying to modify the collection.

Example:

Collection<String> firstCollection = new ArrayList<String>();
Collection<String> secondCollection = Collections.unmodifiableCollection(firstCollection);
firstCollection.add("hello");
firstCollection.add("from");
firstCollection.add("codeGym");

//secondCollection.add("have a error");
System.out.println(secondCollection); //[hello, from, codeGym]

The Collections.unmodifiableCollection() method returns a wrapper over the collection passed to it. If you call its get() , size() methods , then everything will work. However, when calling the add() , set() , remove() methods , you will get an exception.

java.lang.UnsupportedOperationException
at org.apache.commons.collections.collection.UnmodifiableCollection.add(UnmodifiableCollection.java:75)

In fact, the method is already marked as deprecated and it is recommended to use Collections.unmodifiableCollection(Collection<? extends T> c) instead .

Collection<String> firstCollection = new ArrayList<String>();
Collection<String> secondCollection =
Collections.unmodifiableCollection(firstCollection);
1
Task
Module 3. Java Professional, level 20, lesson 4
Locked
Which Operation is Being Performed?
task4308
1
Task
Module 3. Java Professional, level 20, lesson 4
Locked
Which Operation is Being Performed? 2
task4309
1
Task
Module 3. Java Professional, level 20, lesson 4
Locked
Which Operation is Being Performed? 3
task4310
1
Task
Module 3. Java Professional, level 20, lesson 4
Locked
What operation is being performed? 4
task4311
1
Task
Module 3. Java Professional, level 20, lesson 4
Locked
Anti-Hacker
task4312
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION