Shuffling Collections In Java

1. Overview

In this quick article, we’ll see how we can shuffle a collection in Java. Java has a built-in method for shuffling List objects — we’ll utilize it for other collections as well.

2. Shuffling a List

We’ll use the method java.util.Collections.shuffle, which takes as input a List and shuffles it in-place. By in-place, we mean that it shuffles the same list as passed in input instead of creating a new one with shuffled elements.

Let’s look at a quick example showing how to shuffle a List:

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

There’s a second version of java.util.Collections.shuffle that also accepts as input a custom source of randomness. This can be used to make shuffling a deterministic process if we have such a requirement for our application.

Let’s use this second variant to achieve the same shuffling on two lists:

List<String> students_1 = Arrays.asList("Foo", "Bar", "Baz", "Qux");
List<String> 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. Thus, after shuffling, both lists will contain elements in the exact same order.

3. Shuffling Elements of Unordered Collections

We may want to shuffle other collections as well such as Set, Map, or Queue, for example, but all these collections are unordered — they don’t maintain any specific order.

Some implementations, such as LinkedHashMap, or a Set with a Comparator – do maintain a fixed order, thus we cannot shuffle them either.

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

Let’s see a quick example of shuffling elements of a Map:

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

List<Map.Entry<Integer, String>> shuffledStudentEntries
 = new ArrayList<>(studentsById.entrySet());
Collections.shuffle(shuffledStudentEntries);

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

Similarly, we can shuffle elements of a Set:

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

4. Conclusion

In this quick tutorial, we saw how to use java.util.Collections.shuffle to shuffle various collections in Java.

This naturally works directly with a List, and we can utilize it indirectly to randomize the order of elements in other collections as well. We can also control the shuffling process by providing a custom source of randomness and make it deterministic.

As usual, all code demonstrated in this article is available over on GitHub.

Related posts:

Send an email using the SMTP protocol
JUnit 5 @Test Annotation
Using JWT with Spring Security OAuth
Batch Processing with Spring Cloud Data Flow
Spring Boot - Tracing Micro Service Logs
Java Program to Find the Mode in a Data Set
Tạo chương trình Java đầu tiên sử dụng Eclipse
Java Program to Check whether Undirected Graph is Connected using BFS
Tạo số và chuỗi ngẫu nhiên trong Java
Java Program to Perform Polygon Containment Test
Spring Boot - Twilio
Java Program to do a Breadth First Search/Traversal on a graph non-recursively
Understanding Memory Leaks in Java
Java – Reader to String
Giới thiệu java.io.tmpdir
Guide to Spring Cloud Kubernetes
Connect through a Proxy
Java Program to Implement Pairing Heap
Java Program to Check whether Directed Graph is Connected using BFS
Java Program to Decode a Message Encoded Using Playfair Cipher
Vấn đề Nhà sản xuất (Producer) – Người tiêu dùng (Consumer) và đồng bộ hóa các luồng trong Java
Java Program to Check Whether a Directed Graph Contains a Eulerian Cycle
Upload and Display Excel Files with Spring MVC
Java Map With Case-Insensitive Keys
Comparing Two HashMaps in Java
Spring Boot - Tomcat Deployment
Java Program to Implement Efficient O(log n) Fibonacci generator
Java Program to Print only Odd Numbered Levels of a Tree
Giới thiệu Aspect Oriented Programming (AOP)
Đồng bộ hóa các luồng trong Java
Java Program to Implement the Hill Cypher
Loại bỏ các phần tử trùng trong một ArrayList như thế nào trong Java 8?