Added limit(), which will retain up to the first N elements of a Collection

git-svn-id: https://samskivert.googlecode.com/svn/trunk@2571 6335cc39-0255-0410-8fd6-9bcaacd3b74c
This commit is contained in:
ray.j.greenwell
2009-06-04 23:10:33 +00:00
parent ed70c50606
commit 17d7492248
@@ -72,6 +72,32 @@ public class CollectionUtil
return col;
}
/**
* Modify the specified Collection so that only the first <code>limit</code> elements
* remain, as determined by iteration order. If the Collection is smaller than limit,
* it is unmodified.
*/
public static <T> void limit (Collection<T> col, int limit)
{
int size = col.size();
if (size > limit) {
if (col instanceof List) {
((List) col).subList(limit, size).clear();
} else {
Iterator<T> 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