18 Useful Collections Utility Methods

In this article, we will learn the useful Collections utility methods. You can use these Collections utility methods in your day to day project work. This post provides a list of 18 useful and commonly used Collections utility methods.
Utility methods perform common, often reused functions and they don't require to have object level state, that is they tend to be global functions.
Don't forget to checkout very useful Java CollectionsUtils Class

1. isEmpty(Collection<?> collection)

Return true if the supplied Collection is null or empty. Otherwise, return false.
public static boolean isEmpty(Collection<?> collection) {
    return (collection == null || collection.isEmpty());
}

2. isNotEmpty(Collection<?> collection)

Return true if the supplied Collection is not null or not empty. Otherwise, return false.
public static boolean isNotEmpty(Collection<?> collection) {
    return !isEmpty(collection);
}
Note that this method internally class isEmpty() method.

3. isEmptyMap(Map, ?> map)

Return true if the supplied Map is null or empty. Otherwise, return false.
public static boolean isEmptyMap(Map<?, ?> map) {
    return (map == null || map.isEmpty());
}

4. isNotEmptyMap(Map, ?> map)

Return true if the supplied Map is not null or not empty. Otherwise, return false.
public static boolean isNotEmptyMap(Map<?, ?> map) {
    return !isEmptyMap(map);
}
Note that this method internally class isEmptyMap() method.

5. toObjectArray(Object source)

Convert the given array (which may be a primitive array) to an object array (if necessary of primitive wrapper objects).
public static Object[] toObjectArray(Object source) {
    if (source instanceof Object[]) {
          return (Object[]) source;
    }
    if (source == null) {
         return new Object[0];
    }
    if (!source.getClass().isArray()) {
         throw new IllegalArgumentException("Source is not an array: " + source);
    }
    int length = Array.getLength(source);
    if (length == 0) {
         return new Object[0];
    }
    Class<?> wrapperType = Array.get(source, 0).getClass();
    Object[] newArray = (Object[]) Array.newInstance(wrapperType, length);
    for (int i = 0; i < length; i++) {
         newArray[i] = Array.get(source, i);
    }
    return newArray;
}

6. mergeArrayIntoCollection(Object array, Collection collection)

Merge the given array into the given Collection.
@SuppressWarnings("unchecked")
public static <E> void mergeArrayIntoCollection(Object array, Collection<E> collection) {
     Object[] arr = toObjectArray(array);
    for (Object elem : arr) {
         collection.add((E) elem);
    }
}

7. mergePropertiesIntoMap(Properties props, Map<K, V> map)

Merge the given Properties instance into the given Map, copying all properties (key-value pairs) over.
Uses Properties.propertyNames() to even catch default properties linked into the original Properties instance.
public static <K, V> void mergePropertiesIntoMap(Properties props, Map<K, V> map) {
    if (props != null) {
        for (Enumeration<?> en = props.propertyNames(); en.hasMoreElements();) {
            String key = (String) en.nextElement();
            Object value = props.get(key);
            if (value == null) {
                // Allow for defaults fallback or potentially overridden
                // accessor...
                value = props.getProperty(key);
            }
            map.put((K) key, (V) value);
        }
    }
}

8. contains(Iterator<?> iterator, Object element)

Check whether the given Iterator contains the given element.
public static boolean contains(Iterator<?> iterator, Object element) {
    if (iterator != null) {
         while (iterator.hasNext()) {
              Object candidate = iterator.next();
              if (nullSafeEquals(candidate, element)) {
                  return true;
              }
         }
    }
    return false;
}

9. containsInstance(Collection<?> collection, Object element)

Check whether the given Collection contains the given element instance.
Enforces the given instance to be present, rather than returning true for an equal element as well.
public static boolean containsInstance(Collection<?> collection, Object element) {
    if (collection != null) {
         for (Object candidate : collection) {
             if (candidate == element) {
                 return true;
             }
         }
    }
    return false;
}

10. containsAny(Collection> source, Collection> candidates)

Return true if any element in 'candidates' is contained in 'source'; otherwise returns false.
public static boolean containsAny(Collection<?> source, Collection<?> candidates) {
    if (isEmpty(source) || isEmpty(candidates)) {
         return false;
    }
    for (Object candidate : candidates) {
        if (source.contains(candidate)) {
             return true;
        }
    }
    return false;
}

11. hasUniqueObject(Collection<?> collection)

Determine whether the given Collection only contains a single unique object.
public static boolean hasUniqueObject(Collection<?> collection) {
     if (isEmpty(collection)) {
         return false;
     }
     boolean hasCandidate = false;
     Object candidate = null;
     for (Object elem : collection) {
         if (!hasCandidate) {
              hasCandidate = true;
              candidate = elem;
         } else if (candidate != elem) {
              return false;
         }
     }
     return true;
}

12. lastElement(List list)

Retrieve the last element of the given List, accessing the highest index.
public static <T> T lastElement(List<T> list) {
    if (isEmpty(list)) {
        return null;
    }
    return list.get(list.size() - 1);
}

13. nullSafeEquals(Object o1, Object o2)

Determine if the given objects are equal, returning true if both are null or false if only one is null.
Compares arrays with Arrays.equals, performing an equality check based on the array elements rather than the array reference.
public static boolean nullSafeEquals(Object o1, Object o2) {
    if (o1 == o2) {
        return true;
    }
    if (o1 == null || o2 == null) {
        return false;
    }
    if (o1.equals(o2)) {
        return true;
    }
    if (o1.getClass().isArray() && o2.getClass().isArray()) {
        return arrayEquals(o1, o2);
    }
    return false;
}

14. reverseArray(Object[] array)

Reverses the order of the given array.
public static void reverseArray(final Object[] array) {
    int i = 0;
    int j = array.length - 1;
    Object tmp;

    while (j > i) {
         tmp = array[j];
         array[j] = array[i];
         array[i] = tmp;
         j--;
         i++;
    }
}

15. size(Collection c) and size(Map m)

This method is null-safe and doesn't need to check for null.
Returns the size of the specified collection or 0 if the collection is null.
public static int size(Collection c) {
    return c != null ? c.size() : 0;
}

public static int size(Map m) {
    return m != null ? m.size() : 0;
}

16. isSubList(List l1, List<? super T> l)

This method returns true if the given list contains a given sublist.
public static <T> boolean isSubList(List<T> l1, List<? super T> l) {
    Iterator<? super T> it = l.iterator();
    for (T o1 : l1) {
         if (!it.hasNext()) {
             return false;
         }
         Object o = it.next();
         while ((o == null && !(o1 == null)) || (o != null && !o.equals(o1))) {
             if (!it.hasNext()) {
                 return false;
             }
             o = it.next();
         }
     }
     return true;
}

17. diff(Collection list1, Collection list2)

Returns all objects in list1 that are not in list2.
public static <T> Collection<T> diff(Collection<T> list1, Collection<T> list2) {
    Collection<T> diff = new ArrayList<>();
    for (T t : list1) {
         if (!list2.contains(t)) {
              diff.add(t);
         }
    }
    return diff;
}

18. getFirstItem(Collection collection, T defaultValue)

Retrieves the first item from a collection.
public static <T> T getFirstItem(final Collection<T> collection, final T defaultValue) {
    if (collection == null) {
         return defaultValue;
    }

    final Iterator<T> iterator = collection.iterator();
    return iterator.hasNext() ? iterator.next() : defaultValue;
}
Note that the popular frameworks like Spring, Hibernate and Apache projects use this kind of common String utility classes or methods as reusable methods.

If this article really helps you then let me know in the comment section so that I will prepare similar articles for you.

Check out top complete collections developers guide on Collections Framework Developer Guide

Please write comments, if you want to give any suggestions or feedback about this article would be appreciated.

If you like my articles and want similar kind of stuff, connect with me on Google +,  FacebookGitHub, and StackOverflow.

Check out our top viewed Java Guides and Java/J2EE Best practices. I hope you like it.

Happy Learning and Keep Coding !!!!.

Comments

  1. Very productive and useful utility methods. Thanks Ramesh

    ReplyDelete
  2. for a long time I am waiting for such a insightful blog. keep up the good work. Thanks Ramesh

    ReplyDelete

Post a Comment