Java集合工具包commons-collections

Java Apache Commons Collections 入门指南:从萌新到高手 想象一下,如果你需要处理大量的集合数据,没有 Apache Commons Collections 的帮助,那将会是一场灾难。而 Apache Commons Collections 就像是一位魔法师,能够帮你自动处理这些复杂的任务,让你的代码更加简洁明了。Apache Commons Collections 提供了许多强大的特性,可以帮助我们更高效地进行集合数据的操作。我们的目标是创建一个包含一些整数的列表,并使用 Apache Commons Collections 的工具方法来处理这些数据。 阅读详情
<dependency>
   <groupId>commons-collections</groupId>
   <artifactId>commons-collections</artifactId>
   <version>3.2.2</version>
</dependency>

ListUtils

package org.apache.commons.collections;

public class ListUtils {

    /**
	* 不可变的空集合
	*/
    public static final List EMPTY_LIST = Collections.EMPTY_LIST;
    
    public ListUtils() {
    }

    /**
	* 返回两个集合共有的元素
	*/
    public static List intersection(final List list1, final List list2) {
        final ArrayList result = new ArrayList();
        final Iterator iterator = list2.iterator();

        while (iterator.hasNext()) {
            final Object o = iterator.next();

            if (list1.contains(o)) {
                result.add(o);
            }
        }

        return result;
    }

    /**
     * 从第一个集合中去掉第二个集合中包含的元素
     */
    public static List subtract(final List list1, final List list2) {
        final ArrayList result = new ArrayList(list1);
        final Iterator iterator = list2.iterator();

        while (iterator.hasNext()) {
            result.remove(iterator.next());
        }

        return result;
    }

    /**
     * 取第一个集合和第二个集合所有的元素,并去除两个集合中重复的元素
     */ 
    public static List sum(final List list1, final List list2) {
        return subtract(union(list1, list2), intersection(list1, list2));
    }

    /**
     * 将两个集合合并成一个新的集合
	 */
    public static List union(final List list1, final List list2) {
        final ArrayList result = new ArrayList(list1);
        result.addAll(list2);
        return result;
    }

    /**
     * 判断两个集合是否相等
     */
    public static boolean isEqualList(final Collection list1, final Collection list2) {
        if (list1 == list2) {
            return true;
        }
        if (list1 == null || list2 == null || list1.size() != list2.size()) {
            return false;
        }

        Iterator it1 = list1.iterator();
        Iterator it2 = list2.iterator();
        Object obj1 = null;
        Object obj2 = null;

        while (it1.hasNext() && it2.hasNext()) {
            obj1 = it1.next();
            obj2 = it2.next();

            if (!(obj1 == null ? obj2 == null : obj1.equals(obj2))) {
                return false;
            }
        }

        return !(it1.hasNext() || it2.hasNext());
    }
    
    /**
     * 生成一个集合的hashcode
     */
    public static int hashCodeForList(final Collection list) {
        if (list == null) {
            return 0;
        }
        int hashCode = 1;
        Iterator it = list.iterator();
        Object obj = null;
        
        while (it.hasNext()) {
            obj = it.next();
            hashCode = 31 * hashCode + (obj == null ? 0 : obj.hashCode());
        }
        return hashCode;
    }   

    /**
     * 返回第一个集合中的元素在第一个集合中存在的一个新集合
     */
    public static List retainAll(Collection collection, Collection retain) {
        List list = new ArrayList(Math.min(collection.size(), retain.size()));

        for (Iterator iter = collection.iterator(); iter.hasNext();) {
            Object obj = iter.next();
            if (retain.contains(obj)) {
                list.add(obj);
            }
        }
        return list;
    }

    /**
     * 返回从第一个集合中移除掉remove集合中包含的元素的新集合
     */
    public static List removeAll(Collection collection, Collection remove) {
        List list = new ArrayList();
        for (Iterator iter = collection.iterator(); iter.hasNext();) {
            Object obj = iter.next();
            if (remove.contains(obj) == false) {
                list.add(obj);
            }
        }
        return list;
    }

    /**
     * 返回一个同步的List
     */
    public static List synchronizedList(List list) {
        return SynchronizedList.decorate(list);
    }

    /**
     * 返回一个不可修改的List
     */
    public static List unmodifiableList(List list) {
        return UnmodifiableList.decorate(list);
    }

    /**
     * 返回一个有断言功能List,传入的Predicate在执行add的时候对添加的元素进行校验,校验不通过则抛出IllegalArgumentException
     */
    public static List predicatedList(List list, Predicate predicate) {
        return PredicatedList.decorate(list, predicate);
    }

    /**
     * 返回一个可以添加指定元素类型的List,其他同predicatedList方法
     */
    public static List typedList(List list, Class type) {
        return TypedList.decorate(list, type);
    }
    
    /**
     * 返回一个修饰后的列表,在add和set的时候对元素进行转换后再执行相关操作
     */
    public static List transformedList(List list, Transformer transformer) {
        return TransformedList.decorate(list, transformer);
    }
    
    /**
     * 返回一个LazyList,当调用get方法时,如果索引超出列表长度,列表会自动增长(可以通过一个工厂获得超出索引位置的值)
	 * LazyList和GrowthList都可以实现对修饰的列表进行增长,但是LazyList发生在get时候,而GrowthList发生在set和add时候。
     */
    public static List lazyList(List list, Factory factory) {
        return LazyList.decorate(list, factory);
    }

    /**
     * 返回一个FixedSizeList,修饰一个防止添加/删除的固定大小的列表。add/remove/clear/retain操作是不被支持的
     */
    public static List fixedSizeList(List list) {
        return FixedSizeList.decorate(list);
    }

}

CursorableLinkedList

CursorableLinkedList是List的一种实现,提供了一个列表迭代器并且允许修改列表。CursorableLinkedList支持所有可选列表的操作。它继承自AbstractLinkedList,提供了stack/queue/dequeue的操作。这个类的主要功能是能够在同一时间修改列表和迭代器。listIterator()和cursor()方法都提供了访问一个继承自ListIterator的Cursor实例。游标允许更改列表时并发修改迭代器。需要注意的是,iterator()方法和子列表不会提供这种光标行为。CursorableLinkedList不是线程同步的。

public class CursorableLinkedListTest
{
   @Test
   public void test()
   {
      CursorableLinkedList linkedList = new CursorableLinkedList();
      linkedList.add("center");
      linkedList.addFirst("first");
      linkedList.addLast("last");
      System.out.println(linkedList);
      Cursor cursor = linkedList.cursor();
      if (cursor.hasNext())
      {
         Object o = cursor.next();
         System.out.println("使用游标移除元素:" + o);
         cursor.remove();
      }
      cursor.close();
      System.out.println(linkedList);
      Iterator<?> iterator = linkedList.iterator();
      if (iterator.hasNext())
      {
         Object o = iterator.next();
         System.out.println("使用迭代器移除元素:" + o);
         iterator.remove();
      }
      System.out.println(linkedList);
   }
}

 

CollectionUtils

package org.apache.commons.collections;

public class CollectionUtils {

    private static Integer INTEGER_ONE = new Integer(1);

    /**
     * 一个不可修改的List
     */
    public static final Collection EMPTY_COLLECTION = UnmodifiableCollection.decorate(new ArrayList());

    public CollectionUtils() {
    }

    /**
     * 两个集合的并集,且将a和b中包含的相同元素去重。如果a或者b中包含多个相同的元素,则取重复次数多的那个集合中的次数
     */
    public static Collection union(final Collection a, final Collection b) {
        ArrayList list = new ArrayList();
        Map mapa = getCardinalityMap(a);
        Map mapb = getCardinalityMap(b);
        Set elts = new HashSet(a);
        elts.addAll(b);
        Iterator it = elts.iterator();
        while(it.hasNext()) {
            Object obj = it.next();
            for(int i=0,m=Math.max(getFreq(obj,mapa),getFreq(obj,mapb));i<m;i++) {
                list.add(obj);
            }
        }
        return list;
    }

    /**
     * 取两个集合中的交集
     */
    public static Collection intersection(final Collection a, final Collection b) {
        ArrayList list = new ArrayList();
        Map mapa = getCardinalityMap(a);
        Map mapb = getCardinalityMap(b);
        Set elts = new HashSet(a);
        elts.addAll(b);
        Iterator it = elts.iterator();
        while(it.hasNext()) {
            Object obj = it.next();
            for(int i=0,m=Math.min(getFreq(obj,mapa),getFreq(obj,mapb));i<m;i++) {
                list.add(obj);
            }
        }
        return list;
    }

    /**
     * 取两个集合中的差集
     */
    public static Collection disjunction(final Collection a, final Collection b) {
        ArrayList list = new ArrayList();
        Map mapa = getCardinalityMap(a);
        Map mapb = getCardinalityMap(b);
        Set elts = new HashSet(a);
        elts.addAll(b);
        Iterator it = elts.iterator();
        while(it.hasNext()) {
            Object obj = it.next();
            for(int i=0,m=((Math.max(getFreq(obj,mapa),getFreq(obj,mapb)))-(Math.min(getFreq(obj,mapa),getFreq(obj,mapb))));i<m;i++) {
                list.add(obj);
            }
        }
        return list;
    }

    /**
     * 从集合a中移除集合b中的元素
     */
    public static Collection subtract(final Collection a, final Collection b) {
        ArrayList list = new ArrayList( a );
        for (Iterator it = b.iterator(); it.hasNext();) {
            list.remove(it.next());
        }
        return list;
    }

    /**
     * 判断集合1和集合2是否包含相同的元素
     */
    public static boolean containsAny(final Collection coll1, final Collection coll2) {
        if (coll1.size() < coll2.size()) {
            for (Iterator it = coll1.iterator(); it.hasNext();) {
                if (coll2.contains(it.next())) {
                    return true;
                }
            }
        } else {
            for (Iterator it = coll2.iterator(); it.hasNext();) {
                if (coll1.contains(it.next())) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 统计集合中包含的元素的基数,并用Map结构存储,key元素值,value为key出现的次数
     */
    public static Map getCardinalityMap(final Collection coll) {
        Map count = new HashMap();
        for (Iterator it = coll.iterator(); it.hasNext();) {
            Object obj = it.next();
            Integer c = (Integer) (count.get(obj));
            if (c == null) {
                count.put(obj,INTEGER_ONE);
            } else {
                count.put(obj,new Integer(c.intValue() + 1));
            }
        }
        return count;
    }

    /**
     * 判断集合a是否是集合b的子集
     */
    public static boolean isSubCollection(final Collection a, final Collection b) {
        Map mapa = getCardinalityMap(a);
        Map mapb = getCardinalityMap(b);
        Iterator it = a.iterator();
        while (it.hasNext()) {
            Object obj = it.next();
            if (getFreq(obj, mapa) > getFreq(obj, mapb)) {
                return false;
            }
        }
        return true;
    }

    /**
     * 判断集合a是否是集合b的完全子集
     */
    public static boolean isProperSubCollection(final Collection a, final Collection b) {
        return (a.size() < b.size()) && CollectionUtils.isSubCollection(a,b);
    }

    /**
     * 判断两个集合是否相等
     */
    public static boolean isEqualCollection(final Collection a, final Collection b) {
        if(a.size() != b.size()) {
            return false;
        } else {
            Map mapa = getCardinalityMap(a);
            Map mapb = getCardinalityMap(b);
            if(mapa.size() != mapb.size()) {
                return false;
            } else {
                Iterator it = mapa.keySet().iterator();
                while(it.hasNext()) {
                    Object obj = it.next();
                    if(getFreq(obj,mapa) != getFreq(obj,mapb)) {
                        return false;
                    }
                }
                return true;
            }
        }
    }

    /**
     * 返回某个元素在集合中的基数
     */
    public static int cardinality(Object obj, final Collection coll) {
        if (coll instanceof Set) {
            return (coll.contains(obj) ? 1 : 0);
        }
        if (coll instanceof Bag) {
            return ((Bag) coll).getCount(obj);
        }
        int count = 0;
        if (obj == null) {
            for (Iterator it = coll.iterator();it.hasNext();) {
                if (it.next() == null) {
                    count++;
                }
            }
        } else {
            for (Iterator it = coll.iterator();it.hasNext();) {
                if (obj.equals(it.next())) {
                    count++;
                }
            }
        }
        return count;
    }

    /** 
     * 返回集合中和断言匹配的第一个元素
     */
    public static Object find(Collection collection, Predicate predicate) {
        if (collection != null && predicate != null) {
            for (Iterator iter = collection.iterator(); iter.hasNext();) {
                Object item = iter.next();
                if (predicate.evaluate(item)) {
                    return item;
                }
            }
        }
        return null;
    }
    
    /** 
     * 对集合中的每个元素执行闭包操作
     */
    public static void forAllDo(Collection collection, Closure closure) {
        if (collection != null && closure != null) {
            for (Iterator it = collection.iterator(); it.hasNext();) {
                closure.execute(it.next());
            }
        }
    }

    /** 
     * 将集合中与断言不匹配的元素移除
     */
    public static void filter(Collection collection, Predicate predicate) {
        if (collection != null && predicate != null) {
            for (Iterator it = collection.iterator(); it.hasNext();) {
                if (predicate.evaluate(it.next()) == false) {
                    it.remove();
                }
            }
        }
    }

    /** 
     * 将集合中的元素按照输入Transformer进行转换
     */
    public static void transform(Collection collection, Transformer transformer) {
        if (collection != null && transformer != null) {
            if (collection instanceof List) {
                List list = (List) collection;
                for (ListIterator it = list.listIterator(); it.hasNext();) {
                    it.set(transformer.transform(it.next()));
                }
            } else {
                Collection resultCollection = collect(collection, transformer);
                collection.clear();
                collection.addAll(resultCollection);
            }
        }
    }

    /** 
     * 统计集合中和断言匹配的元素的个数
     */
    public static int countMatches(Collection inputCollection, Predicate predicate) {
        int count = 0;
        if (inputCollection != null && predicate != null) {
            for (Iterator it = inputCollection.iterator(); it.hasNext();) {
                if (predicate.evaluate(it.next())) {
                    count++;
                }
            }
        }
        return count;
    }

    /** 
     * 判断集中是否存在与断言匹配的元素
     */
    public static boolean exists(Collection collection, Predicate predicate) {
        if (collection != null && predicate != null) {
            for (Iterator it = collection.iterator(); it.hasNext();) {
                if (predicate.evaluate(it.next())) {
                    return true;
                }
            }
        }
        return false;
    }

    /** 
     * 提取集合中与断言匹配的元素加入到新集合中
     */
    public static Collection select(Collection inputCollection, Predicate predicate) {
        ArrayList answer = new ArrayList(inputCollection.size());
        select(inputCollection, predicate, answer);
        return answer;
    }

    /** 
     * Selects all elements from input collection which match the given predicate
     * and adds them to outputCollection.
     * <p>
     * If the input collection or predicate is null, there is no change to the 
     * output collection.
     * 
     * @param inputCollection  the collection to get the input from, may be null
     * @param predicate  the predicate to use, may be null
     * @param outputCollection  the collection to output into, may not be null
     */
    public static void select(Collection inputCollection, Predicate predicate, Collection outputCollection) {
        if (inputCollection != null && predicate != null) {
            for (Iterator iter = inputCollection.iterator(); iter.hasNext();) {
                Object item = iter.next();
                if (predicate.evaluate(item)) {
                    outputCollection.add(item);
                }
            }
        }
    }
    
    /**
     * Selects all elements from inputCollection which don't match the given predicate
     * into an output collection.
     * <p>
     * If the input predicate is <code>null</code>, the result is an empty list.
     * 
     * @param inputCollection  the collection to get the input from, may not be null
     * @param predicate  the predicate to use, may be null
     * @return the elements <b>not</b> matching the predicate (new list)
     * @throws NullPointerException if the input collection is null
     */
    public static Collection selectRejected(Collection inputCollection, Predicate predicate) {
        ArrayList answer = new ArrayList(inputCollection.size());
        selectRejected(inputCollection, predicate, answer);
        return answer;
    }
    
    /** 
     * Selects all elements from inputCollection which don't match the given predicate
     * and adds them to outputCollection.
     * <p>
     * If the input predicate is <code>null</code>, no elements are added to <code>outputCollection</code>.
     * 
     * @param inputCollection  the collection to get the input from, may be null
     * @param predicate  the predicate to use, may be null
     * @param outputCollection  the collection to output into, may not be null
     */
    public static void selectRejected(Collection inputCollection, Predicate predicate, Collection outputCollection) {
        if (inputCollection != null && predicate != null) {
            for (Iterator iter = inputCollection.iterator(); iter.hasNext();) {
                Object item = iter.next();
                if (predicate.evaluate(item) == false) {
                    outputCollection.add(item);
                }
            }
        }
    }
    
    /** 
     * Returns a new Collection consisting of the elements of inputCollection transformed
     * by the given transformer.
     * <p>
     * If the input transformer is null, the result is an empty list.
     * 
     * @param inputCollection  the collection to get the input from, may not be null
     * @param transformer  the transformer to use, may be null
     * @return the transformed result (new list)
     * @throws NullPointerException if the input collection is null
     */
    public static Collection collect(Collection inputCollection, Transformer transformer) {
        ArrayList answer = new ArrayList(inputCollection.size());
        collect(inputCollection, transformer, answer);
        return answer;
    }
    
    /** 
     * Transforms all elements from the inputIterator with the given transformer 
     * and adds them to the outputCollection.
     * <p>
     * If the input iterator or transformer is null, the result is an empty list.
     * 
     * @param inputIterator  the iterator to get the input from, may be null
     * @param transformer  the transformer to use, may be null
     * @return the transformed result (new list)
     */
    public static Collection collect(Iterator inputIterator, Transformer transformer) {
        ArrayList answer = new ArrayList();
        collect(inputIterator, transformer, answer);
        return answer;
    }
    
    /** 
     * Transforms all elements from inputCollection with the given transformer 
     * and adds them to the outputCollection.
     * <p>
     * If the input collection or transformer is null, there is no change to the 
     * output collection.
     *
     * @param inputCollection  the collection to get the input from, may be null
     * @param transformer  the transformer to use, may be null
     * @param outputCollection  the collection to output into, may not be null
     * @return the outputCollection with the transformed input added
     * @throws NullPointerException if the output collection is null
     */
    public static Collection collect(Collection inputCollection, final Transformer transformer, final Collection outputCollection) {
        if (inputCollection != null) {
            return collect(inputCollection.iterator(), transformer, outputCollection);
        }
        return outputCollection;
    }

    /** 
     * Transforms all elements from the inputIterator with the given transformer 
     * and adds them to the outputCollection.
     * <p>
     * If the input iterator or transformer is null, there is no change to the 
     * output collection.
     *
     * @param inputIterator  the iterator to get the input from, may be null
     * @param transformer  the transformer to use, may be null
     * @param outputCollection  the collection to output into, may not be null
     * @return the outputCollection with the transformed input added
     * @throws NullPointerException if the output collection is null
     */
    public static Collection collect(Iterator inputIterator, final Transformer transformer, final Collection outputCollection) {
        if (inputIterator != null && transformer != null) {
            while (inputIterator.hasNext()) {
                Object item = inputIterator.next();
                Object value = transformer.transform(item);
                outputCollection.add(value);
            }
        }
        return outputCollection;
    }

    //-----------------------------------------------------------------------
    /**
     * Adds an element to the collection unless the element is null.
     * 
     * @param collection  the collection to add to, must not be null
     * @param object  the object to add, if null it will not be added
     * @return true if the collection changed
     * @throws NullPointerException if the collection is null
     * @since Commons Collections 3.2
     */
    public static boolean addIgnoreNull(Collection collection, Object object) {
        return (object == null ? false : collection.add(object));
    }
    
    /**
     * Adds all elements in the iteration to the given collection.
     * 
     * @param collection  the collection to add to, must not be null
     * @param iterator  the iterator of elements to add, must not be null
     * @throws NullPointerException if the collection or iterator is null
     */
    public static void addAll(Collection collection, Iterator iterator) {
        while (iterator.hasNext()) {
            collection.add(iterator.next());
        }
    }
    
    /**
     * Adds all elements in the enumeration to the given collection.
     * 
     * @param collection  the collection to add to, must not be null
     * @param enumeration  the enumeration of elements to add, must not be null
     * @throws NullPointerException if the collection or enumeration is null
     */
    public static void addAll(Collection collection, Enumeration enumeration) {
        while (enumeration.hasMoreElements()) {
            collection.add(enumeration.nextElement());
        }
    }    
    
    /** 
     * Adds all elements in the array to the given collection.
     * 
     * @param collection  the collection to add to, must not be null
     * @param elements  the array of elements to add, must not be null
     * @throws NullPointerException if the collection or array is null
     */
    public static void addAll(Collection collection, Object[] elements) {
        for (int i = 0, size = elements.length; i < size; i++) {
            collection.add(elements[i]);
        }
    }    
    
    /**
     * Given an Object, and an index, returns the nth value in the
     * object.
     * <ul>
     * <li>If obj is a Map, returns the nth value from the <b>keySet</b> iterator, unless 
     *     the Map contains an Integer key with integer value = idx, in which case the
     *     corresponding map entry value is returned.  If idx exceeds the number of entries in
     *     the map, an empty Iterator is returned.
     * <li>If obj is a List or an array, returns the nth value, throwing IndexOutOfBoundsException,
     *     ArrayIndexOutOfBoundsException, resp. if the nth value does not exist.
     * <li>If obj is an iterator, enumeration or Collection, returns the nth value from the iterator,
     *     returning an empty Iterator (resp. Enumeration) if the nth value does not exist.
     * <li>Returns the original obj if it is null or not a Collection or Iterator.
     * </ul>
     * 
     * @param obj  the object to get an index of, may be null
     * @param idx  the index to get
     * @throws IndexOutOfBoundsException
     * @throws ArrayIndexOutOfBoundsException
     *
     * @deprecated use {@link #get(Object, int)} instead. Will be removed in v4.0
     */
    public static Object index(Object obj, int idx) {
        return index(obj, new Integer(idx));
    }
    
    /**
     * Given an Object, and a key (index), returns the value associated with
     * that key in the Object. The following checks are made:
     * <ul>
     * <li>If obj is a Map, use the index as a key to get a value. If no match continue.
     * <li>Check key is an Integer. If not, return the object passed in.
     * <li>If obj is a Map, get the nth value from the <b>keySet</b> iterator.
     *     If the Map has fewer than n entries, return an empty Iterator.
     * <li>If obj is a List or an array, get the nth value, throwing IndexOutOfBoundsException,
     *     ArrayIndexOutOfBoundsException, resp. if the nth value does not exist.
     * <li>If obj is an iterator, enumeration or Collection, get the nth value from the iterator,
     *     returning an empty Iterator (resp. Enumeration) if the nth value does not exist.
     * <li>Return the original obj.
     * </ul>
     * 
     * @param obj  the object to get an index of
     * @param index  the index to get
     * @return the object at the specified index
     * @throws IndexOutOfBoundsException
     * @throws ArrayIndexOutOfBoundsException
     *
     * @deprecated use {@link #get(Object, int)} instead. Will be removed in v4.0
     */
    public static Object index(Object obj, Object index) {
        if(obj instanceof Map) {
            Map map = (Map)obj;
            if(map.containsKey(index)) {
                return map.get(index);
            }
        }
        int idx = -1;
        if(index instanceof Integer) {
            idx = ((Integer)index).intValue();
        }
        if(idx < 0) {
            return obj;
        } 
        else if(obj instanceof Map) {
            Map map = (Map)obj;
            Iterator iterator = map.keySet().iterator();
            return index(iterator, idx);
        } 
        else if(obj instanceof List) {
            return ((List)obj).get(idx);
        } 
        else if(obj instanceof Object[]) {
            return ((Object[])obj)[idx];
        } 
        else if(obj instanceof Enumeration) {
            Enumeration it = (Enumeration)obj;
            while(it.hasMoreElements()) {
                idx--;
                if(idx == -1) {
                    return it.nextElement();
                } else {
                    it.nextElement();
                }
            }
        } 
        else if(obj instanceof Iterator) {
            return index((Iterator)obj, idx);
        }
        else if(obj instanceof Collection) {
            Iterator iterator = ((Collection)obj).iterator();
            return index(iterator, idx);
        }
        return obj;
    }

    private static Object index(Iterator iterator, int idx) {
        while(iterator.hasNext()) {
            idx--;
            if(idx == -1) {
                return iterator.next();
            } else {
                iterator.next();
            }
        }
        return iterator;
    }
    
    /**
     * Returns the <code>index</code>-th value in <code>object</code>, throwing
     * <code>IndexOutOfBoundsException</code> if there is no such element or 
     * <code>IllegalArgumentException</code> if <code>object</code> is not an 
     * instance of one of the supported types.
     * <p>
     * The supported types, and associated semantics are:
     * <ul>
     * <li> Map -- the value returned is the <code>Map.Entry</code> in position 
     *      <code>index</code> in the map's <code>entrySet</code> iterator, 
     *      if there is such an entry.</li>
     * <li> List -- this method is equivalent to the list's get method.</li>
     * <li> Array -- the <code>index</code>-th array entry is returned, 
     *      if there is such an entry; otherwise an <code>IndexOutOfBoundsException</code>
     *      is thrown.</li>
     * <li> Collection -- the value returned is the <code>index</code>-th object 
     *      returned by the collection's default iterator, if there is such an element.</li>
     * <li> Iterator or Enumeration -- the value returned is the
     *      <code>index</code>-th object in the Iterator/Enumeration, if there
     *      is such an element.  The Iterator/Enumeration is advanced to 
     *      <code>index</code> (or to the end, if <code>index</code> exceeds the 
     *      number of entries) as a side effect of this method.</li>
     * </ul>
     * 
     * @param object  the object to get a value from
     * @param index  the index to get
     * @return the object at the specified index
     * @throws IndexOutOfBoundsException if the index is invalid
     * @throws IllegalArgumentException if the object type is invalid
     */
    public static Object get(Object object, int index) {
        if (index < 0) {
            throw new IndexOutOfBoundsException("Index cannot be negative: " + index);
        }
        if (object instanceof Map) {
            Map map = (Map) object;
            Iterator iterator = map.entrySet().iterator();
            return get(iterator, index);
        } else if (object instanceof List) {
            return ((List) object).get(index);
        } else if (object instanceof Object[]) {
            return ((Object[]) object)[index];
        } else if (object instanceof Iterator) {
            Iterator it = (Iterator) object;
            while (it.hasNext()) {
                index--;
                if (index == -1) {
                    return it.next();
                } else {
                    it.next();
                }
            }
            throw new IndexOutOfBoundsException("Entry does not exist: " + index);
        } else if (object instanceof Collection) {
            Iterator iterator = ((Collection) object).iterator();
            return get(iterator, index);
        } else if (object instanceof Enumeration) {
            Enumeration it = (Enumeration) object;
            while (it.hasMoreElements()) {
                index--;
                if (index == -1) {
                    return it.nextElement();
                } else {
                    it.nextElement();
                }
            }
            throw new IndexOutOfBoundsException("Entry does not exist: " + index);
        } else if (object == null) {
            throw new IllegalArgumentException("Unsupported object type: null");
        } else {
            try {
                return Array.get(object, index);
            } catch (IllegalArgumentException ex) {
                throw new IllegalArgumentException("Unsupported object type: " + object.getClass().getName());
            }
        }
    }
    
    /** 
     * Gets the size of the collection/iterator specified.
     * <p>
     * This method can handles objects as follows
     * <ul>
     * <li>Collection - the collection size
     * <li>Map - the map size
     * <li>Array - the array size
     * <li>Iterator - the number of elements remaining in the iterator
     * <li>Enumeration - the number of elements remaining in the enumeration
     * </ul>
     * 
     * @param object  the object to get the size of
     * @return the size of the specified collection
     * @throws IllegalArgumentException thrown if object is not recognised or null
     * @since Commons Collections 3.1
     */
    public static int size(Object object) {
        int total = 0;
        if (object instanceof Map) {
            total = ((Map) object).size();
        } else if (object instanceof Collection) {
            total = ((Collection) object).size();
        } else if (object instanceof Object[]) {
            total = ((Object[]) object).length;
        } else if (object instanceof Iterator) {
            Iterator it = (Iterator) object;
            while (it.hasNext()) {
                total++;
                it.next();
            }
        } else if (object instanceof Enumeration) {
            Enumeration it = (Enumeration) object;
            while (it.hasMoreElements()) {
                total++;
                it.nextElement();
            }
        } else if (object == null) {
            throw new IllegalArgumentException("Unsupported object type: null");
        } else {
            try {
                total = Array.getLength(object);
            } catch (IllegalArgumentException ex) {
                throw new IllegalArgumentException("Unsupported object type: " + object.getClass().getName());
            }
        }
        return total;
    }
    
    /**
     * Checks if the specified collection/array/iterator is empty.
     * <p>
     * This method can handles objects as follows
     * <ul>
     * <li>Collection - via collection isEmpty
     * <li>Map - via map isEmpty
     * <li>Array - using array size
     * <li>Iterator - via hasNext
     * <li>Enumeration - via hasMoreElements
     * </ul>
     * <p>
     * Note: This method is named to avoid clashing with
     * {@link #isEmpty(Collection)}.
     * 
     * @param object  the object to get the size of, not null
     * @return true if empty
     * @throws IllegalArgumentException thrown if object is not recognised or null
     * @since Commons Collections 3.2
     */
    public static boolean sizeIsEmpty(Object object) {
        if (object instanceof Collection) {
            return ((Collection) object).isEmpty();
        } else if (object instanceof Map) {
            return ((Map) object).isEmpty();
        } else if (object instanceof Object[]) {
            return ((Object[]) object).length == 0;
        } else if (object instanceof Iterator) {
            return ((Iterator) object).hasNext() == false;
        } else if (object instanceof Enumeration) {
            return ((Enumeration) object).hasMoreElements() == false;
        } else if (object == null) {
            throw new IllegalArgumentException("Unsupported object type: null");
        } else {
            try {
                return Array.getLength(object) == 0;
            } catch (IllegalArgumentException ex) {
                throw new IllegalArgumentException("Unsupported object type: " + object.getClass().getName());
            }
        }
    }

    //-----------------------------------------------------------------------
    /**
     * Null-safe check if the specified collection is empty.
     * <p>
     * Null returns true.
     * 
     * @param coll  the collection to check, may be null
     * @return true if empty or null
     * @since Commons Collections 3.2
     */
    public static boolean isEmpty(Collection coll) {
        return (coll == null || coll.isEmpty());
    }

    /**
     * Null-safe check if the specified collection is not empty.
     * <p>
     * Null returns false.
     * 
     * @param coll  the collection to check, may be null
     * @return true if non-null and non-empty
     * @since Commons Collections 3.2
     */
    public static boolean isNotEmpty(Collection coll) {
        return !CollectionUtils.isEmpty(coll);
    }

    //-----------------------------------------------------------------------
    /**
     * Reverses the order of the given array.
     * 
     * @param array  the array to reverse
     */
    public static void reverseArray(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++;
        }
    }

    private static final int getFreq(final Object obj, final Map freqMap) {
        Integer count = (Integer) freqMap.get(obj);
        if (count != null) {
            return count.intValue();
        }
        return 0;
    }

    /**
     * Returns true if no more elements can be added to the Collection.
     * <p>
     * This method uses the {@link BoundedCollection} interface to determine the
     * full status. If the collection does not implement this interface then
     * false is returned.
     * <p>
     * The collection does not have to implement this interface directly.
     * If the collection has been decorated using the decorators subpackage
     * then these will be removed to access the BoundedCollection.
     *
     * @param coll  the collection to check
     * @return true if the BoundedCollection is full
     * @throws NullPointerException if the collection is null
     */
    public static boolean isFull(Collection coll) {
        if (coll == null) {
            throw new NullPointerException("The collection must not be null");
        }
        if (coll instanceof BoundedCollection) {
            return ((BoundedCollection) coll).isFull();
        }
        try {
            BoundedCollection bcoll = UnmodifiableBoundedCollection.decorateUsing(coll);
            return bcoll.isFull();
            
        } catch (IllegalArgumentException ex) {
            return false;
        }
    }

    /**
     * Get the maximum number of elements that the Collection can contain.
     * <p>
     * This method uses the {@link BoundedCollection} interface to determine the
     * maximum size. If the collection does not implement this interface then
     * -1 is returned.
     * <p>
     * The collection does not have to implement this interface directly.
     * If the collection has been decorated using the decorators subpackage
     * then these will be removed to access the BoundedCollection.
     *
     * @param coll  the collection to check
     * @return the maximum size of the BoundedCollection, -1 if no maximum size
     * @throws NullPointerException if the collection is null
     */
    public static int maxSize(Collection coll) {
        if (coll == null) {
            throw new NullPointerException("The collection must not be null");
        }
        if (coll instanceof BoundedCollection) {
            return ((BoundedCollection) coll).maxSize();
        }
        try {
            BoundedCollection bcoll = UnmodifiableBoundedCollection.decorateUsing(coll);
            return bcoll.maxSize();
            
        } catch (IllegalArgumentException ex) {
            return -1;
        }
    }

    //-----------------------------------------------------------------------
    /**
     * Returns a collection containing all the elements in <code>collection</code>
     * that are also in <code>retain</code>. The cardinality of an element <code>e</code>
     * in the returned collection is the same as the cardinality of <code>e</code>
     * in <code>collection</code> unless <code>retain</code> does not contain <code>e</code>, in which
     * case the cardinality is zero. This method is useful if you do not wish to modify
     * the collection <code>c</code> and thus cannot call <code>c.retainAll(retain);</code>.
     * 
     * @param collection  the collection whose contents are the target of the #retailAll operation
     * @param retain  the collection containing the elements to be retained in the returned collection
     * @return a <code>Collection</code> containing all the elements of <code>collection</code>
     * that occur at least once in <code>retain</code>.
     * @throws NullPointerException if either parameter is null
     * @since Commons Collections 3.2
     */
    public static Collection retainAll(Collection collection, Collection retain) {
        return ListUtils.retainAll(collection, retain);
    }

    /**
     * Removes the elements in <code>remove</code> from <code>collection</code>. That is, this
     * method returns a collection containing all the elements in <code>c</code>
     * that are not in <code>remove</code>. The cardinality of an element <code>e</code>
     * in the returned collection is the same as the cardinality of <code>e</code>
     * in <code>collection</code> unless <code>remove</code> contains <code>e</code>, in which
     * case the cardinality is zero. This method is useful if you do not wish to modify
     * the collection <code>c</code> and thus cannot call <code>collection.removeAll(remove);</code>.
     * 
     * @param collection  the collection from which items are removed (in the returned collection)
     * @param remove  the items to be removed from the returned <code>collection</code>
     * @return a <code>Collection</code> containing all the elements of <code>collection</code> except
     * any elements that also occur in <code>remove</code>.
     * @throws NullPointerException if either parameter is null
     * @since Commons Collections 3.2
     */
    public static Collection removeAll(Collection collection, Collection remove) {
        return ListUtils.removeAll(collection, remove);
    }

    //-----------------------------------------------------------------------
    /**
     * Returns a synchronized collection backed by the given collection.
     * <p>
     * You must manually synchronize on the returned buffer's iterator to 
     * avoid non-deterministic behavior:
     *  
     * <pre>
     * Collection c = CollectionUtils.synchronizedCollection(myCollection);
     * synchronized (c) {
     *     Iterator i = c.iterator();
     *     while (i.hasNext()) {
     *         process (i.next());
     *     }
     * }
     * </pre>
     * 
     * This method uses the implementation in the decorators subpackage.
     * 
     * @param collection  the collection to synchronize, must not be null
     * @return a synchronized collection backed by the given collection
     * @throws IllegalArgumentException  if the collection is null
     */
    public static Collection synchronizedCollection(Collection collection) {
        return SynchronizedCollection.decorate(collection);
    }

    /**
     * Returns an unmodifiable collection backed by the given collection.
     * <p>
     * This method uses the implementation in the decorators subpackage.
     *
     * @param collection  the collection to make unmodifiable, must not be null
     * @return an unmodifiable collection backed by the given collection
     * @throws IllegalArgumentException  if the collection is null
     */
    public static Collection unmodifiableCollection(Collection collection) {
        return UnmodifiableCollection.decorate(collection);
    }

    /**
     * Returns a predicated (validating) collection backed by the given collection.
     * <p>
     * Only objects that pass the test in the given predicate can be added to the collection.
     * Trying to add an invalid object results in an IllegalArgumentException.
     * It is important not to use the original collection after invoking this method,
     * as it is a backdoor for adding invalid objects.
     *
     * @param collection  the collection to predicate, must not be null
     * @param predicate  the predicate for the collection, must not be null
     * @return a predicated collection backed by the given collection
     * @throws IllegalArgumentException  if the Collection is null
     */
    public static Collection predicatedCollection(Collection collection, Predicate predicate) {
        return PredicatedCollection.decorate(collection, predicate);
    }

    /**
     * Returns a typed collection backed by the given collection.
     * <p>
     * Only objects of the specified type can be added to the collection.
     * 
     * @param collection  the collection to limit to a specific type, must not be null
     * @param type  the type of objects which may be added to the collection
     * @return a typed collection backed by the specified collection
     */
    public static Collection typedCollection(Collection collection, Class type) {
        return TypedCollection.decorate(collection, type);
    }
    
    /**
     * Returns a transformed bag backed by the given collection.
     * <p>
     * Each object is passed through the transformer as it is added to the
     * Collection. It is important not to use the original collection after invoking this 
     * method, as it is a backdoor for adding untransformed objects.
     *
     * @param collection  the collection to predicate, must not be null
     * @param transformer  the transformer for the collection, must not be null
     * @return a transformed collection backed by the given collection
     * @throws IllegalArgumentException  if the Collection or Transformer is null
     */
    public static Collection transformedCollection(Collection collection, Transformer transformer) {
        return TransformedCollection.decorate(collection, transformer);
    }

}

 

 

 

Java Apache Commons Collections:高级进阶与刨根问底 在Java的世界里,Apache Commons Collections库就像是一位身怀绝技的老朋友,它总能在你最需要的时候伸出援手。Apache Commons Collections是一套强大的集合工具包,它提供了许多实用的工具类和接口实现,帮助开发者更好地处理Java中的集合类型。Predicates是Apache Commons Collections中的一种强大工具,它可以帮助我们过滤集合中的元素。迭代器在处理集合时非常有用,让我们看看IteratorUtils是如何让我们的生活更简单的。 阅读详情

相关推荐

【问题解析】Matlab Function的易错点(Variable Size)

Matlab Function的易错点

CrazyRabbit的博客 9878

缺少org.apache.commons.collections.CollectionUtils?

也许你正在寻找的jar是apache commons-collections: <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-collections4</artifactId> <version>4.1</version> </dependency> 要么 &l

乐乐的博客 8939

微机原理与接口技术第六版周荷琴课后习题答案及解析(期末重点)

第二章 1.8086/8088CPU可直接寻址多少个内存(字节)单元?多少个I/O端口?它们的外部数据总线各有多少根? 8086/8088CPU使用的是20位地址总线,因此可以直接寻址2的20次方个内存单元(即1,048,576),每个单元大小为1字节,因此可以直接寻址2的20次方个字节的内存。 8086/8088CPU有64K个I/O端口,每个端口占用1字节的地址空间,因此可以直接寻址6...

Wmicheng的博客 1万+

commons-collections包中的常用的工具类

commons-collections包中的常用的工具类 <dependency> <groupId>commons-collections</groupId> <artifactId>commons-collections</artifactId> &...

weixin_34107739的博客 825

告别手动干预:深入浅出LPDDR5的Background ZQ校准与DVFSQ切换避坑指南

本文深入解析LPDDR5的Background ZQ校准与DVFSQ切换技术,帮助工程师实现DRAM阻抗校准的自动化管理。通过详细配置指南和实战案例,揭示如何避免动态电压调节下的模式切换陷阱,提升信号完整性和系统能效。特别适合嵌入式系统和移动终端开发者参考。

weixin_30329623的博客 458

996引擎 - 读写变量性能测试

单轮100万次读写,取3轮平均耗时(毫秒),有效读取率均为100%,数值越小性能越优。

灵台方寸山斜月三星洞 250

CommonsCollections1

是Apache软件基金会的项目,曾经隶属于Jakarta项目。Commons的目的是提供可重用的、解决各种实际的通用问题且开源的Java代码。Proper(是一些已发布的项目)、Sandbox(是一些正在开发的项目)和Dormant(是一些刚启动或者已经停止维护的项目)。包为Java标准的提供了相当好的补充。在此基础上对其常用的数据结构操作进行了很好的封装、抽象和补充。让我们在开发应用程序的过程中,既保证了性能,同时也能大大简化代码。

qq_63928796的博客 1530

【FPGA教程案例87】加解密1——基于FPGA的AES加解密算法verilog实现

DES已走到了它生命的尽头。56比特密钥实在太小,虽然三重DES可以解决密钥长度的问题,但是DES的设计主要针对硬件实现,而今在许多领域,需要用软件方法来实现它,在这种情况下,它的效率相对较低。1997年4月15日美国国家标准和技术研究所(NIST)发起征集AES(Advanced Encryption Standard)算法的活动,并成立了AES工作组。目的是为了确定一个非保密的、公开披露的、全球免费使用的加密算法,用于保护下一世纪政府的敏感信息。这里,我们对AES的基本原理进行介绍:

FPGA/MATLAB学习教程/源码/项目合作开发 2548

synchronized

基础synchronized 是java中的是一种同步锁机制,可以用来修饰类、方法、代码块。 修饰类 /** * 修饰类: * 多个线程调用不同对象执行synchronized修饰的类时,同步只对synchronized修饰的类有效 */ public void decorateClass() { System.out.prin

RoySite的博客 285

STM32G474开发板初步入门与编程实战

STM32G474开发板提供了一种快速评估、原型设计和开发STM32G474应用的方式。它搭载了STM32G474RET6微控制器,配备512KB闪存、128KB RAM,支持各种常见的接口和连接,如USB、I2C、SPI、UART等。板载ST-Link/V2-1调试器/编程器,简化了开发过程。

qq_38334677的博客 4968

钢结构焊接连接工艺

钢结构焊接连接工艺

wwdoffice950426的博客 65

commons-collections包工具类用法

commons-collections 小结

哈 2967

第11.4节 混合储能系统能量管理

混合储能系统(HESS)的能量管理策略采用分层架构实现多时间尺度优化:调度层(小时级)进行经济优化,协调层(秒级)基于频率分解分配功率,执行层(毫秒级)实现快速跟踪。深度强化学习(DRL)方法通过定义状态空间、动作空间和多目标奖励函数,能有效处理系统不确定性和多目标优化问题。HESS性能评估需综合技术指标(如调节性能Kp值、设备寿命指标)和经济指标(净现值NPV、平准化储能成本LCOS),并遵循"建模-仿真-实验"的闭环流程。

技术工作者 252

Bag集合工具类(apache-commons-collections3.2工具包)在java中的使用

 Bag 是在 org.apache.commons.collections 包中定义的接口 ,也是集合的一种扩充工具类,当然结合用JDK中的map类进行相应的逻辑处理,也能实现Bag类的功能,但apache推出来肯定有它的原因和用处,知道有这么一个类了解它大概的用法,开发的时候真遇到这种情况,知道有这么个工具在你身边等着你用呢。 此接口定义源码: public interface Ba

Java我人生的技术博客 1万+

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

jdk-8u144-linux-x64.tar.gz.

该资源为搭建Linux系统Java环境用,资源的后缀为tar.gz格式的压缩包

Commons Collections的简易理解

Apache Commons Collections是一个用来处理集合Collection的开源工具包,比如你可以用来将一个对象拷贝多份并存放到一个Bag对象中(这个看来没有多大用处),得到两个集合里相同的元素,删除一个集合里的元素并返回删除的元素,还有除了通过一个集合里的key得到value外,还可以通过value 得到key,也就是说这个集合里的value是唯一的,另外还可以将一个集合里的ke

编程reborn 1846

廖雪峰Python教程[完整版]

廖雪峰的python教程整理的,已经排好版了,而且还是完整的,适合小白

Spring下commons,bean,io等工具包的常用API方法

一。   1。 StringUtils.abbreviate(str, maxWidth)   用来

linwei_1029的专栏 2341

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

Java基础类(七):CollectionUtils工具类

发发发

mingyuli的博客 1921

Apache Commons工具集简介

1、Commons BeanUtils http://jakarta.apache.org/commons/beanutils/index.html 说明:针对Bean的一个工具集。由于Bean往往是有一堆get和set组成,所以BeanUtils也是在此基础上进行一些包装。 使用示例:功能有很多,网站上有详细介绍。一个比较常用的功能是Bean Copy,也就是copy bean的属性。如果...

前前 132

java 8 list属性判空_Java世界最常用的工具类库

Apache CommonsApache Commons有很多子项目,常用的项目如下BeanUtils提供了一系列对java bean的操作,读取和设置属性值等@Data User map和bean的互相转换// bean->map 我们将对象放在缓存中通常用redis中的hash,如下# 这种场景下map和bean的互相转换的工具类就特别有用Codec常见的编码,解码方法封装// Base...

weixin_39769039的博客 523

java list 交集 并集 差集 去重复并集

Array基本操作 import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class TestCollection { public static void main(String[] args) { List list1 = new ArrayList...

155

探查 Struts 包的含义

commons-beanutils.jar 简单易用的 Java 反射和内省 API 包装器commons-collections.jar 一组用于扩展和增强 Java Collections Framework 的类 commons-digester.jar 通常用于分析 XML 配置文件的 XML 到 Java 对象映射实用程序 commons-lang.jar 一组公用实用程序类,可以为

勇敢de心 643

java file 到 byte[]_Java程序员常用的工具类库

Apache CommonsApache Commons有很多子项目,常用的项目如下@Data public class User { private String username; private String password; }设置和获得属性User user = new User(); BeanUtils.setProperty(user, "username", "li...

weixin_39541681的博客 158

Struts2 使用JSON所需包

<br />json-lib-2.1.jar    //json核心<br />commons-lang-2.3.jar  //需要这个包中的某些Exception<br />commons-collections-3.2.jar  //采集功能<br />commons-beanutils-1.7.0.jar  //bean工具<br />ezmorph-1.0.3.jar<br /> 

zzycgfans的blog 1289

ssm框架中各jar包的作用

spring-aop-*.jar     :    里面包含了针对面向切面的接口,通常Spring等其他具备动态植入功能的框架依赖此包。 spring-aspects-*.jar :   这是Spring AOP所要用到的。 commons-codec-*.jar    :    主要包括加密核心算法。比如 MD5、SHA128,或者常规加密解密算法:BASE64。 common

weixin_42080201的博客 1556
上一篇: Linux Cron 表达式
下一篇: Java集合工具包com.google.guava:guava
AlferWei
博客等级 码龄11年 42粉丝 137原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值