We can use Collections.shuffle() method to shuffle elements in linked list in java. It generates different order of output every time when it is invoked.
Syntax:
Collections.shuffle(linkedList);
Example:
package com.w3schools; import java.util.Collections; import java.util.LinkedList; public class Test { public static void main(String args[]){ LinkedList<String> linkedList = new LinkedList<String>(); linkedList.add("Jai"); linkedList.add("Mahesh"); linkedList.add("Naren"); linkedList.add("Vivek"); linkedList.add("Vishal"); linkedList.add("Hemant"); System.out.println("Actual LinkedList:"+linkedList); Collections.shuffle(linkedList); System.out.println("Results after shuffle operation:" + linkedList); Collections.shuffle(linkedList); System.out.println("Results after shuffle operation:" + linkedList); } } |
Output
Actual LinkedList:[Jai, Mahesh, Naren, Vivek, Vishal, Hemant] Results after shuffle operation:[Hemant, Mahesh, Jai, Naren, Vishal, Vivek] Results after shuffle operation:[Hemant, Mahesh, Vishal, Naren, Vivek, Jai] |