Java: Retrieve a random discontinuous Sublist of an ArrayList (most efficient way)
arraylist, java, random, set, sublist
Solution
Warning: This is coded in my browser. It may not even compile!
Using Collections.shuffle and List.subList will do the job.
public static <T> List<T> randomSubList(List<T> list, int newSize) {
list = new ArrayList<>(list);
Collections.shuffle(list);
return list.subList(0, newSize);
}
Problem
put simply my question is: What is the most efficient way to retrieve a random discontinuous sublist of an ArrayList with a given size. The following is my own design, which works but seems a little clunky to me. It is my first JAVA program by the way so please excuse if my code or question is not according to best practice ;) Remarks: - my list does not contain duplicates - I guessed that it might be faster to remove items instead of adding them if the AimSize is more than half of the size of the original list ``` public ArrayList<Vokabel> subList(int AimSize) { ArrayList<Vokabel> tempL = new ArrayList<Vokabel>(); Random r = new Random(); LinkedHashSet<Vokabel> tempS = new LinkedHashSet<Vokabel>(); tempL = originalList; // If the size is to big just leave the list and change size // (in the real code there is no pass-by-value problem ;) if (!(tempL.size() > AimSize)) { AimSize = tempL.size(); // set to avoid duplicates and get a random order } else if (2* AimSize < tempL.size()) { while (tempS.size() < AimSize) { tempS.add(tempL.get(r.nextInt(tempL.size()))); } tempL = new ArrayList<Vokabel>(tempS); // little optimization if it involves less loops // to delete entries to get to the right size, than to add them // the List->Set->List conversion at the end is there to reorder the items } else { while (tempL.size() > AimSize) { tempL.remove(r.nextInt(tempL.size())); } tempL = new ArrayList<Vokabel>(new LinkedHashSet<Vokabel>(tempL)); } return tempL; } ```