mercredi 18 février 2015

Java: Retrieve a random Sublist of an ArrayList (most efficient way)

put simply my question is: What is the most efficient way to retrieve a random 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;
}

Aucun commentaire:

Enregistrer un commentaire