Class CollectionUtils


  • public class CollectionUtils
    extends Object
    A utility class that provides re-usable functionality that relates to Java collections.
    Author:
    Guus der Kinderen, guus.der.kinderen@gmail.com
    • Constructor Detail

      • CollectionUtils

        public CollectionUtils()
    • Method Detail

      • distinctByKey

        public static <T> Predicate<T> distinctByKey​(Function<? super T,​Object> keyExtractor)
        Returns a stateful stream filter that, once applied to a stream, returns a stream consisting of the distinct elements (according to the specified key).

        The implementation of Stream.distinct() can be used to return a stream that has distinct elements, based on the implementation of Object.equals(Object). That implementation does not allow to filter a stream based on one property of each object. The implementation of provided by this method does.

        Type Parameters:
        T - Stream element type.
        Parameters:
        keyExtractor - A function to extract the desired key from the stream objects (cannot be null).
        Returns:
        A filter
        See Also:
        Stack Overflow: Java Lambda Stream Distinct() on arbitrary key?
      • findDuplicates

        @Nonnull
        public static <V> Set<V> findDuplicates​(@Nonnull
                                                Collection<V>... collections)
        Returns all elements that occur more than exactly once in the combination of all elements from all provided collections.
        Type Parameters:
        V - The type of the entities in the collections.
        Parameters:
        collections - The collection for which to return duplicates
        Returns:
        The duplicates