Executar operação em n elementos distintos aleatórios da coleção usando a API do Streams
No entanto, estou tentando recuperar n elementos aleatórios exclusivos para processamento adicional de uma coleção usando a API Streams no Java 8, sem muita ou nenhuma sorte.
Mais precisamente, eu gostaria de algo assim:
Set<Integer> subList = new HashSet<>();
Queue<Integer> collection = new PriorityQueue<>();
collection.addAll(Arrays.asList(1,2,3,4,5,6,7,8,9));
Random random = new Random();
int n = 4;
while (subList.size() < n) {
subList.add(collection.get(random.nextInt()));
}
sublist.forEach(v -> v.doSomethingFancy());
Eu quero fazê-lo da forma mais eficiente possível.
Isso pode ser feito?
edit: Minha segunda tentativa - embora não seja exatamente o que eu estava buscando:
List<Integer> sublist = new ArrayList<>(collection);
Collections.shuffle(sublist);
sublist.stream().limit(n).forEach(v -> v.doSomethingFancy());
editar: Terceira tentativa (inspirada emHolger), que removerá grande parte da sobrecarga do shuffle se coll.size () for enorme en for pequeno:
int n = // unique element count
List<Integer> sublist = new ArrayList<>(collection);
Random r = new Random();
for(int i = 0; i < n; i++)
Collections.swap(sublist, i, i + r.nextInt(source.size() - i));
sublist.stream().limit(n).forEach(v -> v.doSomethingFancy());