All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.databene.commons.CollectionUtil Maven / Gradle / Ivy

Go to download

'databene commons' is an open source Java library by Volker Bergmann. It provides extensions to the Java core library by utility classes, abstract concepts and concrete implementations.

The newest version!
/*
 * Copyright (C) 2004-2015 Volker Bergmann ([email protected]).
 * All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.databene.commons;

import java.util.*;
import java.lang.reflect.Array;
import java.lang.reflect.Modifier;

import org.databene.commons.collection.SortedList;

/**
 * Provides Collection-related utility methods.
 * Created: 18.12.2006 06:46:24
 */
public final class CollectionUtil {

    public static boolean isEmpty(Collection collection) {
        return (collection == null || collection.size() == 0);
    }

    /**
     * Converts an array into a list.
     * @param array the array to convert into a list.
     * @param  the element type
     * @return a list containing all elements of the given array.
     */
    public static  List toList(T ... array) {
        List result = new ArrayList(array.length);
        for (T item : array)
            result.add(item);
        return result;
    }

    public static  List

toListOfType(Class

type, C ... array) { List

result = new ArrayList

(array.length); for (C item : array) result.add(item); return result; } /** * Creates a HashSet filled with the specified elements * @param elements the content of the Set * @param the element type * @return a HashSet with the elements */ public static Set toSet(T ... elements) { HashSet set = new HashSet(); if (elements != null) for (T element : elements) set.add(element); return set; } public static SortedSet toSortedSet(U ... elements) { TreeSet set = new TreeSet(); for (T element : elements) set.add(element); return set; } public static , U extends T> SortedList toSortedList(U ... elements) { return new SortedList(CollectionUtil.toList(elements), new ComparableComparator()); } public static Set toCharSet(char[] chars) { HashSet set = new HashSet(); if (chars != null) for (char element : chars) set.add(element); return set; } /** * Adds the content of an array to a collection * @param target the collection to be extended * @param values the values to add * @param the collection type * @param the element type * @param the common supertype of the values * @return the collection, extended by the contents of the array */ public static > C add(C target, U ... values) { for (T item : values) target.add(item); return target; } public static List copy(List src, int offset, int length) { List items = new ArrayList(length); for (int i = 0; i < length; i++) items.add(src.get(offset + i)); return items; } @SuppressWarnings("unchecked") public static T[] toArray(Collection source) { if (source.size() == 0) throw new IllegalArgumentException("For empty collections, a componentType needs to be specified."); Class componentType = (Class) source.iterator().next().getClass(); T[] array = (T[]) Array.newInstance(componentType, source.size()); return source.toArray(array); } @SuppressWarnings("unchecked") public static T[] toArray(Collection source, Class componentType) { T[] array = (T[]) Array.newInstance(componentType, source.size()); return source.toArray(array); } @SuppressWarnings("unchecked") public static T[] extractArray(List source, Class componentType, int fromIndex, int toIndex) { T[] array = (T[]) Array.newInstance(componentType, toIndex - fromIndex); return source.subList(fromIndex, toIndex).toArray(array); } public static char[] toCharArray(Collection source) { char[] result = new char[source.size()]; int i = 0; for (Character c : source) result[i++] = c; return result; } public static Map buildMap(K key, V value) { Map map = new HashMap(); map.put(key, value); return map; } @SuppressWarnings({ "unchecked", "rawtypes" }) public static Map buildMap(Object ... keyValuePairs) { Map map = new HashMap(); if (keyValuePairs.length % 2 != 0) throw new IllegalArgumentException("Invalid numer of arguments. " + "It must be even to represent key-value-pairs"); for (int i = 0; i < keyValuePairs.length; i += 2) map.put(keyValuePairs[i], keyValuePairs[i + 1]); return map; } @SuppressWarnings({ "unchecked", "rawtypes" }) public static Map buildOrderedMap(Object ... keyValuePairs) { Map map = new OrderedMap(); if (keyValuePairs.length % 2 != 0) throw new IllegalArgumentException("Invalid numer of arguments. " + "It must be even to represent key-value-pairs"); for (int i = 0; i < keyValuePairs.length; i += 2) map.put(keyValuePairs[i], keyValuePairs[i + 1]); return map; } /** Creates a new instance of a Collection. Abstract interfaces are mapped to a default implementation class. * @param collectionType the type of the collection to be created * @param the type of the requested collection * @param the collection element type * @return an empty instance of the requested collection type */ @SuppressWarnings("unchecked") public static , U> T newInstance(Class collectionType) { if ((collectionType.getModifiers() & Modifier.ABSTRACT) == 0) return BeanUtil.newInstance(collectionType); else if (Collection.class.equals(collectionType) || List.class.equals(collectionType)) return (T) new ArrayList(); else if (SortedSet.class.equals(collectionType)) return (T) new TreeSet(); else if (Set.class.equals(collectionType)) return (T) new TreeSet(); else throw new UnsupportedOperationException("Not a supported collection type: " + collectionType.getName()); } /** Compares two lists for identical content, accepting different order. * @param a1 the first list * @param a2 the second list * @param the generic list type * @return true if both lists have the same content elements, else false */ public static boolean equalsIgnoreOrder(List a1, List a2) { if (a1 == a2) return true; if (a1 == null) return false; if (a1.size() != a2.size()) return false; List l1 = new ArrayList(a1.size()); for (T item : a1) l1.add(item); for (int i = a1.size() - 1; i >= 0; i--) if (a2.contains(a1.get(i))) l1.remove(i); else return false; return l1.size() == 0; } public static V getCaseInsensitive(String key, Map map) { V result = map.get(key); if (result != null || key == null) return result; String lcKey = key.toLowerCase(); for (String candidate : map.keySet()) if (candidate != null && lcKey.equals(candidate.toLowerCase())) return map.get(candidate); return null; } public static boolean containsCaseInsensitive(String key, Map map) { if (map.containsKey(key)) return true; String lcKey = key.toLowerCase(); for (String candidate : map.keySet()) if (candidate != null && lcKey.equals(candidate.toLowerCase())) return true; return false; } public static boolean ofEqualContent(List list, T[] array) { if (list == null || list.isEmpty()) return (array == null || array.length == 0); if (array == null || list.size() != array.length) return false; for (int i = list.size() - 1; i >= 0; i--) if (!NullSafeComparator.equals(list.get(i), array[i])) return false; return true; } public static T lastElement(List list) { return list.get(list.size() - 1); } @SuppressWarnings("rawtypes") private static final List EMPTY_LIST = Collections.emptyList(); @SuppressWarnings("unchecked") public static List emptyList() { return EMPTY_LIST; } @SuppressWarnings("unchecked") public static List extractItemsOfExactType(Class itemType, Collection items) { List result = new ArrayList(); for (S item : items) if (itemType == item.getClass()) result.add((T) item); return result; } @SuppressWarnings("unchecked") public static List extractItemsOfCompatibleType(Class itemType, Collection items) { List result = new ArrayList(); for (S item : items) if (itemType.isAssignableFrom(item.getClass())) result.add((T) item); return result; } public static String formatCommaSeparatedList(Collection collection, Character quoteCharacter) { StringBuilder builder = new StringBuilder(); int i = 0; Iterator iterator = collection.iterator(); while (iterator.hasNext()) { if (i > 0) builder.append(", "); if (quoteCharacter != null) builder.append(quoteCharacter); builder.append(iterator.next()); if (quoteCharacter != null) builder.append(quoteCharacter); i++; } return builder.toString(); } }