Java Shuffle Array | Random Array Program example

Java Shuffle Array is a procedure to randomize data. As you know Array is a collection of similar types of data like a list of Integers or Strings. The shuffling does randomize the data sets and generating a random data set in the array is different.

This tutorial we will look at both example create a random array and shuffle an array in java.

Java Shuffle Array  Random Array Program example

Java shuffle Array example

One way is to do shuffle array is using “Fisher-Yates shuffle” algorithm. This algorithm generates a random number sequence by doing shuffling a data without missing any one from list.

Output: 5 4 1 3 6 2

Shuffle String Array Java

An upper example you saw for Integer Array, the same thing you can do with a String array. See the below example for it. Don’t forget to add the string array parameter in the shuffleArray method.

Output: E A B C F D

Shuffle Array with Java Collection.shuffle() method

You can shuffle Array by using the java collection .shuffle() method. For that, you have to use an Integer class and Convert the array into ArrayList. See the example of java shuffle ArrayList.

Output: [1, 2, 3, 4]
[4, 2, 1, 3]

Java Random Array

Upper examples you saw shuffling of the Java Array where you have already array then shuffling. What if you want a random array within a range? You can do it with the Random Util class as mentioned below example.

Output: 3 8 2 0

Question: How to shuffle the contents of an array?

Answer: its a very easy as the above-mentioned method Fisher-Yates shuffle or random class. Do comment if you have any other method to do it fast and in efficient ways.

Any doubt and example also commented in below section.


Note: This example (Project) is developed in IntelliJ IDEA 2018.2.6 (Community Edition)
JRE: 11.0.1
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.14.1
Java version 11
All Examples are in Java 11, so it may change on different from Java 9 or 10 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.