In this article, we will understand how to shuffle the elements of a collection. The Collection is a framework that provides architecture to store and manipulate the group of objects. Java Collections can achieve all the operations that you perform on a data such as searching, sorting, insertion, manipulation, and deletion.
Below is a demonstration of the same −
Suppose our input is −
Input list: [Java, program, is, fun, and, easy]
The desired output would be −
The shuffled list is: [is, easy, program, and, fun, Java]
Algorithm
Step 1 - START Step 2 - Declare an arraylist namely input_list. Step 3 - Define the values. Step 4 - Using the function shuffle(), we shuffle the elements of the list. Step 5 - Display the result Step 6 - Stop
Example 1
Here, we bind all the operations together under the ‘main’ function.
import java.util.*;
public class Demo {
public static void main(String[] args){
ArrayList<String> input_list = new ArrayList<String>();
input_list.add("Java");
input_list.add("program");
input_list.add("is");
input_list.add("fun");
input_list.add("and");
input_list.add("easy");
System.out.println("The list is defined as:" + input_list);
Collections.shuffle(input_list, new Random());
System.out.println("The shuffled list is: \n" + input_list);
}
}Output
The list is defined as:[Java, program, is, fun, and, easy] The shuffled list is: [is, Java, fun, program, easy, and]
Example 2
Here, we encapsulate the operations into functions exhibiting object oriented programming.
import java.util.*;
public class Demo {
static void shuffle(ArrayList<String> input_list){
Collections.shuffle(input_list, new Random());
System.out.println("The shuffled list is: \n" + input_list);
}
public static void main(String[] args){
ArrayList<String> input_list = new ArrayList<String>();
input_list.add("Java");
input_list.add("program");
input_list.add("is");
input_list.add("fun");
input_list.add("and");
input_list.add("easy");
System.out.println("The list is defined as:" + input_list);
shuffle(input_list);
}
}Output
The list is defined as:[Java, program, is, fun, and, easy] The shuffled list is: [fun, and, Java, easy, is, program]