If you want to chose them randomly but not repeat any, then this would be one way to do it. This avoids shuffling the entire list which isn't necessary for small sample sizes. So it only does as much of a shuffle as required to ensure you don't get repeats. This does alter the list order but does not modify the contents.
String[] piuHigh = { "Destri", "fff", "qbf", "imprinting", "site",
"Hyn", "error", "gloria", "paved", "fullmoon",
"don't remember kpop", "creedFull"};
String[] items = getItems(6, piuHigh);
for (String s : items) {
System.out.println(s);
}
prints something like
paved
Destri
error
fff
creedFull
don't remember kpop
- first check to ensure there are enough items.
- then select one item at random.
- save it for return
- then swap that with the one at the end of the given list
last
is then updated to avoid re-choosing the item just chosen.
public static String[] getItems(int amount, String[] source) {
if (amount > source.length) {
throw new IllegalArgumentException("Insufficient items");
}
String[] selection = new String[amount];
Random r = new Random();
int last = source.length;
for (int i = 0; i < amount; i++) {
int select = r.nextInt(last);
String item = source[select];
selection[i] = item;
source[select] = source[--last];
source[last] = item;
}
return selection;
}