Java Collection Max truncate(Collection coll, int maximumSize)

Here you can find the source of truncate(Collection coll, int maximumSize)

Description

truncate

License

Open Source License

Declaration

public static <T> Collection<T> truncate(Collection<T> coll, int maximumSize) 

Method Source Code

//package com.java2s;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;

import java.util.Iterator;

public class Main {
    public static <T> Collection<T> truncate(Collection<T> coll, int maximumSize) {
        if (coll.size() > maximumSize)
            try {
                Iterator<T> iter = coll.iterator();
                for (int i = 0; i < maximumSize; ++i) {
                    iter.next();/*from  w ww . ja  v  a  2  s.  com*/
                }
                while (iter.hasNext()) {
                    iter.next();
                    iter.remove();
                }
            } catch (Throwable e) {
                e.printStackTrace();
            }
        return coll;
    }

    public static <T, C extends Collection<T>> C remove(C coll, T... items) {
        return minus(coll, items);
    }

    public static <T, C extends Collection<T>, D extends Collection<T>> C remove(C coll, D items) {
        return minus(coll, items);
    }

    public static <T, C extends Collection<T>> C minus(C coll, T... items) {
        coll.removeAll(newList(items));
        return coll;
    }

    public static <T, C extends Collection<T>, D extends Collection<T>> C minus(C coll, D items) {
        return minus(coll, (T[]) items.toArray());
    }

    /**
     * Creates a new {@link ArrayList} and inserts the arguments, {@code ts}.
     * @param ts
     * @return the new {@link ArrayList}
     */
    public static <T> ArrayList<T> newList(T... ts) {
        ArrayList<T> newList = new ArrayList<T>();
        if (ts != null && ts.length > 0) {
            newList.addAll(Arrays.asList(ts));
        }
        return newList;
    }
}

Related

  1. minOrMax(int sign, Collection values)
  2. partitionFixed(int maxNumChunks, Collection coll)
  3. toString(Collection collection, int maxLen)
  4. toString(Collection entries, int max)
  5. transfer(Collection source, Collection dest, int maxElems)
  6. valueOfCollection(Collection c, int maxLength)