From 17d7492248bc13f13de5026a08e91a2f1d6d4377 Mon Sep 17 00:00:00 2001 From: "ray.j.greenwell" Date: Thu, 4 Jun 2009 23:10:33 +0000 Subject: [PATCH] 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 --- .../com/samskivert/util/CollectionUtil.java | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) 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