Collections { public static <T> List<T> selectRandom(int count, Collection<T> collection) { ArrayList<T> result = new ArrayList<>(count); if (collection.size() <= count) { result.addAll(collection); } else { double collectionRest = collection.size(); double resultRest = count; int skipMax = (int) Math.ceil(collectionRest / resultRest); int skip = RANDOM.nextInt(skipMax); for (T item : collection) { collectionRest--; if (skip > 0) { skip--; } else { result.add(item); resultRest--; if (resultRest == 0) { break; } skipMax = (int) Math.ceil(collectionRest / resultRest); skip = RANDOM.nextInt(skipMax); } } } return result; }  static List<T> selectRandom(int count, Collection<T> collection); static T selectRandom(Collection<T> collection);  }
@Test public void ensureSelectRandomReturnsMaximumPossibleItems() throws Exception { List<Integer> list = new LinkedList<>(); for (int i = 0; i < 10; i++) { list.add(i); } assertEquals(9, Collections.selectRandom(9, list).size()); }