I've got a List of Objects, this list could potentially contain thousands of elements.
I want to obtain 10, 20, 34, 56 (whatever size portion the user chooses) subset of those, this subset must be randomly selected and I can't have duplicates.
Would Collections.shuffle() be sufficient for large Lists of POJOs? Or is there a more efficient/safer way of doing this?
Taking my example here, if myStrings had 50,000 Strings in it, would calling Collections.shuffle() be a good idea if you only wanted 5 items?
public class ShuffleMe { public static void main(String[] args) { int NUM_OF_ELEMENTS_TO_PICK = 3; List<String> myStrings = new ArrayList<String>(); myStrings.add("A"); myStrings.add("B"); myStrings.add("C"); myStrings.add("D"); myStrings.add("E"); myStrings.add("F"); Collections.shuffle(myStrings); for (int i = 0; i < NUM_OF_ELEMENTS_TO_PICK; i++) { System.out.println(myStrings.get(i)); } } }
Collections.sort()is because I don't want to have to retrieve all items from a database call if I'll only actually use a few of them, does this alter any answers?