Baralhar coleções em Java

Baralhar coleções em Java

1. Visão geral

Neste artigo rápido, veremoshow we can shuffle a collection in Java. Java tem um método embutido para embaralhar objetosList - vamos utilizá-lo para outras coleções também.

2. Embaralhar uma lista

We’ll use the method [.pl-smi]#java.util.Collections.shuffle [.blob-code-inner] [. pl-smi], que ### leva como entrada umListe embaralha no local. Por local, queremos dizer que ela embaralha a mesma lista que a entrada passada, em vez de criar uma nova com elementos embaralhados.

Vejamos um exemplo rápido que mostra como embaralhar umList:

List students = Arrays.asList("Foo", "Bar", "Baz", "Qux");
Collections.shuffle(students);

There’s a second version of [.pl-smi]#java.util.Collections.shuffle [.blob-code-inner] [. pl-smi]that also accepts as input a custom source of randomness. Isso pode ser usado para tornar o embaralhamento um processo determinístico se tivermos esse requisito para nosso aplicativo.#

[.pl-smi]#Let’s use this second variant to achieve the same shuffling on two lists: #

List students_1 = Arrays.asList("Foo", "Bar", "Baz", "Qux");
List students_2 = Arrays.asList("Foo", "Bar", "Baz", "Qux");

int seedValue = 10;

Collections.shuffle(students_1, new Random(seedValue));
Collections.shuffle(students_2, new Random(seedValue));

assertThat(students_1).isEqualTo(students_2);

When using identical sources of randomness (initialized from same seed value), the generated random number sequence will be the same for both shuffles. Assim, após embaralhar, ambas as listas conterão elementos na mesma ordem.

3. Embaralhando elementos de coleções não ordenadas

We may want to shuffle other collections as well such as Set, Map, or Queue, for example, but all these collections are unordered - eles não mantêm nenhuma ordem específica.

Algumas implementações, comoLinkedHashMap ou aSet comComparator - mantêm uma ordem fixa, portanto, também não podemos embaralhá-los.

No entanto,we can still access their elements randomly by converting them first into a List, then shuffling this List.

Vejamos um exemplo rápido de embaralhamento de elementos de umMap:

Map studentsById = new HashMap<>();
studentsById.put(1, "Foo");
studentsById.put(2, "Bar");
studentsById.put(3, "Baz");
studentsById.put(4, "Qux");

List> shuffledStudentEntries
 = new ArrayList<>(studentsById.entrySet());
Collections.shuffle(shuffledStudentEntries);

List shuffledStudents = shuffledStudentEntries.stream()
  .map(Map.Entry::getValue)
  .collect(Collectors.toList());

Da mesma forma, podemos embaralhar elementos de aSet:

Set students = new HashSet<>(
  Arrays.asList("Foo", "Bar", "Baz", "Qux"));
List studentList = new ArrayList<>(students);
Collections.shuffle(studentList);

4. Conclusão

Neste tutorial rápido, vimos como usar[.pl-smi]#java.util.Collections.shuffle [.blob-code-inner] [. Pl-smi] #para embaralhar várias coleções em Java. ##

Isso naturalmente funciona diretamente com aList,e podemos utilizá-lo indiretamente para randomizar a ordem dos elementos em outras coleções também. Também podemos controlar o processo de embaralhamento, fornecendo uma fonte personalizada de aleatoriedade e torná-la determinística.

Como de costume, todo o código demonstrado neste artigo está disponívelover on GitHub.