diff --git a/src/java/com/samskivert/util/CollectionUtil.java b/src/java/com/samskivert/util/CollectionUtil.java index e2790f6c..ff7f207c 100644 --- a/src/java/com/samskivert/util/CollectionUtil.java +++ b/src/java/com/samskivert/util/CollectionUtil.java @@ -72,6 +72,32 @@ public class CollectionUtil return col; } + /** + * Modify the specified Collection so that only the first limit elements + * remain, as determined by iteration order. If the Collection is smaller than limit, + * it is unmodified. + */ + public static void limit (Collection col, int limit) + { + int size = col.size(); + if (size > limit) { + if (col instanceof List) { + ((List) col).subList(limit, size).clear(); + + } else { + Iterator itr = col.iterator(); + int ii = 0; + for (; ii < limit; ii++) { + itr.next(); + } + for (; ii < size; ii++) { + itr.next(); + itr.remove(); + } + } + } + } + /** * Returns a list containing a random selection of elements from the * specified collection. The total number of elements selected will be