Class CollectionHelper


  • public class CollectionHelper
    extends Object
    Helper methods for collections
    • Method Summary

      All Methods Static Methods Concrete Methods 
      Modifier and Type Method Description
      static <T> void addAll​(Collection<T> collection, T... elements)
      Add all elements to the given collection
      static <T> void addOrRemove​(Collection<T> collection, T value, boolean add)
      Adds or removes a value from the given collection, according to the given flag (true = add, false = remove)
      static <T> Page<T> asPage​(Iterable<T> collection)
      Returns a new Page containing a copy of the given Collection as the total elements
      static <T> Page<T> asPage​(List<T> all, int pageSize, int currentPage)
      Applies the pagination to an in-memory list
      static <T> Page<T> asPage​(T... elements)
      Returns a new Page containing a copy of the given Collection as the total elements
      static <T> Set<T> asSet​(Iterable<T> elements)
      Returns the given elements as a Set, filtering nulls
      static <T> Set<T> asSet​(T... elements)
      Returns the given elements as a Set, filtering nulls
      static <T> Stream<T> asStream​(Iterable<T> iterable)
      Returns a Stream equivalent to the given Iterable.
      static <T> Stream<T> asStream​(Enumeration<T> enumeration)
      Returns a Stream equivalent to the given Enumeration.
      static <T> Stream<T> asStream​(Iterator<T> iterator)
      Returns a Stream equivalent to the given iterator.
      static <T> boolean containsAll​(Collection<T> first, Collection<T> second)  
      static boolean containsAny​(Collection<?> collection, Object... toTest)
      Checks whether the first collection contains at least one element of the second collection
      static boolean containsAny​(Collection<?> collection, Collection<?> toTest)
      Checks whether the first collection contains at least one element of the second collection
      static boolean equals​(Map<?,​?> map1, Map<?,​?> map2)
      Returns whether all keys and values are equals on both maps.
      static <I,​O extends I>
      Stream<O>
      filterByType​(Stream<I> stream, Class<O> subType)
      Returns a filtered Stream containing only the elements which are instances of the given subclass
      static <T> int findIndex​(List<T> list, Predicate<T> test)
      Returns the first index that matches the given predicate
      static <T> T first​(Iterable<T> collection)
      Returns the first element in a collection, or null when the collection is empty or null
      static <T> T first​(T[] value)
      Returns the first element in an array, or null if the array is null or empty
      static Object[] flatten​(Object... input)
      Returns an array comprised of all elements of all objects in the given input.
      static Map<String,​String> flattenKeys​(Map<String,​?> map, String separator)
      Flatten a map containing nested properties into a map.
      static <T> void forEach​(Collection<T> collection, Consumer<T> consumer)
      If the given collection is not null performs the collection.forEach with the given consumer
      static Integer getTotalCount​(Iterable<?> collection)
      Returns the total count of the given collection, handling pages with the Page.getTotalCount() method.
      static int hashCode​(Map<?,​?> map)
      Returns the hashCode of the given Map, by hashing each key and value
      static boolean hasOnlyOneElement​(Collection<?> collection)
      Returns true if the collection has only one element, handling nulls.
      static List<Integer> intRange​(int minInclusive, int maxInclusive)
      Returns a list containing integers in the given interval, inclusive
      static boolean isEmpty​(Iterable<?> collection)
      Checks whether the given collection is null or empty
      static boolean isEmpty​(Object[] array)
      Checks whether the given array is null or empty
      static boolean isEmpty​(Map<?,​?> map)
      Checks whether the given map is null or empty
      static <T> boolean isEmptyIgnoring​(Collection<T> elements, Collection<T> ignored)
      Indicates whether the given collection is empty ignoring the given other collection
      static boolean isNotEmpty​(Iterable<?> collection)
      Checks whether the given collection is not null and not empty
      static boolean isNotEmpty​(Object[] array)
      Checks whether the given array is not null and not empty
      static boolean isNotEmpty​(Map<?,​?> map)
      Checks whether the given map is not null and not empty
      static <T> Iterable<T> iterable​(Enumeration<T> enumeration)
      Returns an Iterable for the given enumeration
      static <T> Iterable<T> iterable​(Iterator<T> iterator)
      Returns an Iterable which returns the given iterator.
      static String join​(Iterable<?> collection, String separator)
      Joins a collection of values into a single string, using the given separator.
      static String join​(Object[] array, String separator)
      Joins an array of values into a single string, using the given separator.
      static <T> T last​(List<T> list)
      Returns the last element of a list, or null if the list is null or empty
      static int length​(Object[] array)
      It returns the array's length supporting null values (returning 0).
      static <I,​O>
      List<O>
      map​(Collection<I> input, Function<I,​O> mapper)
      Maps each collection element, returning the result list
      static <T,​V>
      boolean
      matchesAll​(Collection<T> universe, Collection<V> toMatch, BiPredicate<T,​V> matcher)
      Matches each of the given elements against an universe of available elements.
      static Object maybeUnwrap​(Collection<?> collection)
      Returns: Null if the collection is empty or null The first element if the collection has a single element The collection 'as-is' otherwise
      static Map<String,​Object> nestKeys​(Map<String,​String> map, String separator)
      Nest properties separated by dots in a map.
      static <T> Collection<T> orEmpty​(Collection<T> collection)
      Returns an empty list if the given list is null
      static <T> List<T> orEmpty​(List<T> list)
      Returns an empty list if the given list is null
      static <K,​V>
      Map<K,​V>
      orEmpty​(Map<K,​V> map)
      Returns an empty map if the given map is null
      static <T> Set<T> orEmpty​(Set<T> set)
      Returns an empty set if the given set is null
      static <T> T random​(List<T> list)
      Returns a random item from a collection, handling nulls
      static void removeNulls​(Collection<?> collection)
      Removes any null elements on the given collection
      static int size​(Object[] array)
      Returns the size of the given array, or 0 if null
      static int size​(Collection<?> collection)
      Returns the collection size, handling nulls (returns 0 if the collection is null)
      static int size​(Map<?,​?> map)
      Returns the number of key-value mappings in this map, handling nulls (returns 0 if the map is null)
      static <T extends Comparable<? super T>>
      List<T>
      sort​(Collection<T> collection)
      It sorts the specified collection returning an ordered List.
      If the collection already is a list it return the same instance.
      static <T> List<T> sort​(Collection<T> collection, Comparator<? super T> comparator)
      It sorts the specified collection returning an ordered List.
      If the collection already is a list it return the same instance.
      static <T> List<List<T>> split​(List<T> list, int maxSize)
      Splits the given list into several sub lists, with the given maximum size
      static <T> Iterator<T> toIterator​(Enumeration<T> enumeration)
      Returns an iterator with the same elements as the given enumeration
      static <T> Collection<T> union​(Collection<T> first, Collection<T> second)
      Returns a new list containing all elements of the given lists (first + second).
    • Constructor Detail

      • CollectionHelper

        public CollectionHelper()
    • Method Detail

      • addAll

        @SafeVarargs
        public static <T> void addAll​(Collection<T> collection,
                                      T... elements)
        Add all elements to the given collection
      • addOrRemove

        public static <T> void addOrRemove​(Collection<T> collection,
                                           T value,
                                           boolean add)
        Adds or removes a value from the given collection, according to the given flag (true = add, false = remove)
      • asPage

        public static <T> Page<T> asPage​(Iterable<T> collection)
        Returns a new Page containing a copy of the given Collection as the total elements
      • asPage

        public static <T> Page<T> asPage​(List<T> all,
                                         int pageSize,
                                         int currentPage)
        Applies the pagination to an in-memory list
      • asPage

        @SafeVarargs
        public static <T> Page<T> asPage​(T... elements)
        Returns a new Page containing a copy of the given Collection as the total elements
      • asSet

        public static <T> Set<T> asSet​(Iterable<T> elements)
        Returns the given elements as a Set, filtering nulls
      • asSet

        @SafeVarargs
        public static <T> Set<T> asSet​(T... elements)
        Returns the given elements as a Set, filtering nulls
      • asStream

        public static <T> Stream<T> asStream​(Enumeration<T> enumeration)
        Returns a Stream equivalent to the given Enumeration. If the enumeration is null then returns an empty Stream.
      • asStream

        public static <T> Stream<T> asStream​(Iterable<T> iterable)
        Returns a Stream equivalent to the given Iterable. If the iterable is null then returns an empty Stream.
      • asStream

        public static <T> Stream<T> asStream​(Iterator<T> iterator)
        Returns a Stream equivalent to the given iterator. The returned Stream doesn't need to be closed after a terminal operation, because it will be wrapped in a Stream.flatMap(java.util.function.Function) call, which by definition closes the stream after a terminal operation.
      • containsAll

        public static <T> boolean containsAll​(Collection<T> first,
                                              Collection<T> second)
        Parameters:
        first - the container collection or null
        second - the contained collection or null
        Returns:
        true if the first collection contains all elements of the second one.
        If first is empty/null then it returns true only if second is empty/null too.
        Otherwise it returns true if second is empty/null or first contains all elements of second.
      • containsAny

        public static boolean containsAny​(Collection<?> collection,
                                          Collection<?> toTest)
        Checks whether the first collection contains at least one element of the second collection
      • containsAny

        public static boolean containsAny​(Collection<?> collection,
                                          Object... toTest)
        Checks whether the first collection contains at least one element of the second collection
      • equals

        public static boolean equals​(Map<?,​?> map1,
                                     Map<?,​?> map2)
        Returns whether all keys and values are equals on both maps. Also returns true if both maps are null of if their equals() method return true
      • filterByType

        public static <I,​O extends I> Stream<O> filterByType​(Stream<I> stream,
                                                                   Class<O> subType)
        Returns a filtered Stream containing only the elements which are instances of the given subclass
      • findIndex

        public static <T> int findIndex​(List<T> list,
                                        Predicate<T> test)
        Returns the first index that matches the given predicate
      • first

        public static <T> T first​(Iterable<T> collection)
        Returns the first element in a collection, or null when the collection is empty or null
      • first

        public static <T> T first​(T[] value)
        Returns the first element in an array, or null if the array is null or empty
      • flatten

        public static Object[] flatten​(Object... input)
        Returns an array comprised of all elements of all objects in the given input. If each input is:
        • An Iterable: Add each element returned by Iterable.iterator()
        • An Object[]: Add each array element
        • null: Ignore
        • Anything else: Add the object as is
        This method is not recursive. If there are nested lists of objects, they are kept as they are.
      • flattenKeys

        public static Map<String,​String> flattenKeys​(Map<String,​?> map,
                                                           String separator)
        Flatten a map containing nested properties into a map. Is the inverse operation of nestKeys(Map, String). For example, using dot as separator:
         {
            "a": {
                "a1": {
                    "a2": "x",
                    "a3": "y"
                }
            },
            "b": "z"
         }
         
        becomes:
         {
            "a.a1.a2": "x",
            "a.a1.a3": "y",
            "b": "y"
         }
         
      • forEach

        public static <T> void forEach​(Collection<T> collection,
                                       Consumer<T> consumer)
        If the given collection is not null performs the collection.forEach with the given consumer
      • getTotalCount

        public static Integer getTotalCount​(Iterable<?> collection)
        Returns the total count of the given collection, handling pages with the Page.getTotalCount() method. If the collection is a Page and the configuration is set to skip total count, this method returns null.
      • hashCode

        public static int hashCode​(Map<?,​?> map)
        Returns the hashCode of the given Map, by hashing each key and value
      • hasOnlyOneElement

        public static boolean hasOnlyOneElement​(Collection<?> collection)
        Returns true if the collection has only one element, handling nulls.
        See Also:
        size(Collection)
      • intRange

        public static List<Integer> intRange​(int minInclusive,
                                             int maxInclusive)
        Returns a list containing integers in the given interval, inclusive
      • isEmpty

        public static boolean isEmpty​(Iterable<?> collection)
        Checks whether the given collection is null or empty
      • isEmpty

        public static boolean isEmpty​(Map<?,​?> map)
        Checks whether the given map is null or empty
      • isEmpty

        public static boolean isEmpty​(Object[] array)
        Checks whether the given array is null or empty
      • isEmptyIgnoring

        public static <T> boolean isEmptyIgnoring​(Collection<T> elements,
                                                  Collection<T> ignored)
        Indicates whether the given collection is empty ignoring the given other collection
      • isNotEmpty

        public static boolean isNotEmpty​(Iterable<?> collection)
        Checks whether the given collection is not null and not empty
      • isNotEmpty

        public static boolean isNotEmpty​(Map<?,​?> map)
        Checks whether the given map is not null and not empty
      • isNotEmpty

        public static boolean isNotEmpty​(Object[] array)
        Checks whether the given array is not null and not empty
      • iterable

        public static <T> Iterable<T> iterable​(Iterator<T> iterator)
        Returns an Iterable which returns the given iterator. Useful to use iterators in the enhanced for loop
      • join

        public static String join​(Iterable<?> collection,
                                  String separator)
        Joins a collection of values into a single string, using the given separator. If the collection is null, returns an empty string. If the separator is null, no separator is used.
      • join

        public static String join​(Object[] array,
                                  String separator)
        Joins an array of values into a single string, using the given separator. If the collection is null, returns an empty string. If the separator is null, no separator is used.
      • last

        public static <T> T last​(List<T> list)
        Returns the last element of a list, or null if the list is null or empty
      • length

        public static int length​(Object[] array)
        It returns the array's length supporting null values (returning 0).
      • map

        public static <I,​O> List<O> map​(Collection<I> input,
                                              Function<I,​O> mapper)
        Maps each collection element, returning the result list
      • matchesAll

        public static <T,​V> boolean matchesAll​(Collection<T> universe,
                                                     Collection<V> toMatch,
                                                     BiPredicate<T,​V> matcher)
        Matches each of the given elements against an universe of available elements. A custom predicate is used for matching.
        Parameters:
        universe - The universe of available elements (may be null)
        toMatch - The elements to actually test (may be null)
        Returns:
        true if every element in the collection toMatch matches against any of the elements in the universe collection
      • maybeUnwrap

        public static Object maybeUnwrap​(Collection<?> collection)
        Returns:
        • Null if the collection is empty or null
        • The first element if the collection has a single element
        • The collection 'as-is' otherwise
      • nestKeys

        public static Map<String,​Object> nestKeys​(Map<String,​String> map,
                                                        String separator)
        Nest properties separated by dots in a map. Is the inverse operation of flattenKeys(Map, String). For example, using dot as separator:
         {
            "a.a1.a2": "x",
            "a.a1.a3": "y",
            "b": "y"
         }
         
        becomes:
         {
            "a": {
                "a1": {
                    "a2": "x",
                    "a3": "y"
                }
            },
            "b": "z"
         }
         
      • orEmpty

        public static <T> Collection<T> orEmpty​(Collection<T> collection)
        Returns an empty list if the given list is null
      • orEmpty

        public static <T> List<T> orEmpty​(List<T> list)
        Returns an empty list if the given list is null
      • orEmpty

        public static <K,​V> Map<K,​V> orEmpty​(Map<K,​V> map)
        Returns an empty map if the given map is null
      • orEmpty

        public static <T> Set<T> orEmpty​(Set<T> set)
        Returns an empty set if the given set is null
      • random

        public static <T> T random​(List<T> list)
        Returns a random item from a collection, handling nulls
      • removeNulls

        public static void removeNulls​(Collection<?> collection)
        Removes any null elements on the given collection
      • size

        public static int size​(Collection<?> collection)
        Returns the collection size, handling nulls (returns 0 if the collection is null)
      • size

        public static int size​(Map<?,​?> map)
        Returns the number of key-value mappings in this map, handling nulls (returns 0 if the map is null)
      • size

        public static int size​(Object[] array)
        Returns the size of the given array, or 0 if null
      • sort

        public static <T extends Comparable<? super T>> List<T> sort​(Collection<T> collection)
        It sorts the specified collection returning an ordered List.
        If the collection already is a list it return the same instance. Otherwise it creates a new list. If the input collection is null, returns an empty list.
      • sort

        public static <T> List<T> sort​(Collection<T> collection,
                                       Comparator<? super T> comparator)
        It sorts the specified collection returning an ordered List.
        If the collection already is a list it return the same instance. Otherwise it creates a new list. If the input collection is null, returns an empty list.
      • split

        public static <T> List<List<T>> split​(List<T> list,
                                              int maxSize)
        Splits the given list into several sub lists, with the given maximum size
      • toIterator

        public static <T> Iterator<T> toIterator​(Enumeration<T> enumeration)
        Returns an iterator with the same elements as the given enumeration
      • union

        public static <T> Collection<T> union​(Collection<T> first,
                                              Collection<T> second)
        Returns a new list containing all elements of the given lists (first + second). This method support null for both arguments. If only one of the lists is not null then such list is returned as is. Otherwise a new list is created containing the union (the arguments leave unchanged) This method never return null, if both lists are null/empty an empty list is returnes