Java tutorial
//package com.java2s; import java.util.Collection; import java.util.Iterator; public class Main { public static void trimCollection(Collection collection, int numberOfElements) { if (collection.size() < numberOfElements) { return; } numberOfElements = collection.size() - numberOfElements; Iterator it = collection.iterator(); int counter = 0; while (it.hasNext()) { if (counter <= numberOfElements) { it.next(); counter++; } it.remove(); } } }