How to shuffle elements in LinkedList

This example shows How to shuffle elements in a LinkedList in Java . This example also How to shuffle elements in a LinkedList in Java example using Collections.shuffle() method.

How to Shuffle Elements in LinkedList in Java?

We can shuffle the elements of Java LinkedList with the help of Collections.shuffle() method. Java  Collections.shuffle() method . Let’s see shuffling a LinkedList using Collections.shuffle() method example.

import java.util.Collections;


import java.util.LinkedList;

public class Shuffle {

public static void main(String[] args) {

LinkedList<String> linkedList = new LinkedList<String>();

linkedList.add("Mumbai");
linkedList.add("Delhi");
linkedList.add("Noida");
linkedList.add("Gao");
linkedList.add("Patna");
//print linkedlist
System.out.println("Linklist is = "+linkedList);

//Randomly permutes the specified list using a default
//source of randomness.

Collections.shuffle(linkedList);

for (String str : linkedList) {
System.out.println(str);
}

Collections.shuffle(linkedList);

System.out.println("After Second Shuffle");

for (String str : linkedList) {

System.out.println(str);

}

}

}

Output:

Linklist is = [Mumbai, Delhi, Noida, Gao, Patna]

Gao
Noida
Mumbai
Patna
Delhi

After Second Shuffle

Noida
Patna
Gao
Mumbai
Delhi

In this article we have learned how  to shuffle the elements of Java LinkedList .

 

Leave a Reply

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

+ 84 = 91