How to shuffle elements in a LinkedList in Java

In this tutorial, we will study how to shuffle elements in a LinkedList in Java. For a better understanding, let’s understand what a Linked List is. Linked list elements are stored using pointers. It is an ordered linear structure, similar to an array. In array, elements are stored in a contiguous location, whereas the elements in LinkedList are linked using pointers. Each node of the LinkedList has the element itself and a reference.

shuffle elements in a LinkedList in Java

We can use Collections.shuffle() method to shuffle elements in LinkedList in java. It generates a different order of output every time when the code is run.

Syntax:

Collections.shuffle(linkedList);

Let us check the code of our tutorial :

import java.util.Collections; //importing the Collections framework of Java
import java.util.LinkedList; //importing LinkedList data structure from util package
 
public class Test {
  public static void main(String args[]){
  LinkedList<String> linkedList = new LinkedList<String>(); //defining the data structure LinkedList
  linkedList.add("India"); //adding countries to LinkedList
  linkedList.add("USA");
  linkedList.add("Australia");
  linkedList.add("China");
  linkedList.add("Brazil");
  linkedList.add("London");
  System.out.println("Actual LinkedList:"+linkedList); //original LinkedList
  Collections.shuffle(linkedList); //using collections and shuffling the LinkedList
        System.out.println("Results after shuffle operation:" + linkedList);       //Output 1
        Collections.shuffle(linkedList); //again shuffling the LinkedList
        System.out.println("Results after shuffle operation:" + linkedList); //Output 2
  }

The output of the above code will be

Actual LinkedList:[India, USA, Australia, China, Brazil, London]
Results after shuffle operation:[USA, India, Australia, Brazil, London, China]
Results after shuffle operation:[India, China, London, USA, Brazil, Australia]

First we are printing the actual List, then we are shuffling the list and printing. After the list is shuffled once it is printed. The list is again shuffled for the second time and then printed. Let me know if you need help in the comments section below.

You can also check out How to reverse a LinkedList in Java.

 

Leave a Reply

Your email address will not be published. Required fields are marked *