Java Collection, LinkedList Exercises: Shuffle the elements in a linked list
Last update on December 14 2021 10:52:30 (UTC/GMT +8 hours)How to Shuffle Elements in LinkedList in Java?
LinkedList is a part of the Collection framework present in java.util package. This class is an implementation of the LinkedList data structure which is a linear data structure where the elements are not stored in contiguous locations and every element is a separate object with a data part and address part. The elements are linked using pointers and addresses. Each element is known as a node. Given a LinkedList, the task is to shuffle the LinkedList. These are approaches to solve the problem.
Approach 1 (Using user-define method)
- Create a LinkedList.
- Store its elements in an array by the toArray() method.
- Shuffle the array elements.
- Use ListIterator on the LinkedList and traverse the LinkedList by next() method and store the shuffled data of the Array to the List simultaneously by set() method.
Example
import java.util.*;
public class GFG {
public static void main(String args[])
{
// creating an instance of LinkedList
LinkedList<Object> list = new LinkedList<>();
// adding data to the LinkedList
list.add(45);
list.add("GFG");
list.add(2.56f);
list.add(965.321);
list.add('A');
list.add(true);
System.out.println("The list before shuffle : "
+ list.toString());
System.out.println();
// creating an Array and storing all data of the
// list to the array
Object[] array = list.toArray();
// here we are shuffling more than once
// shuffle 1
arrayShuffle(array);
listDataAdder(array, list);
System.out.println("The list after shuffle 1 : "
+ list.toString());
System.out.println();
// shuffle 2
arrayShuffle(array);
listDataAdder(array, list);
System.out.println("The list after shuffle 2 : "
+ list.toString());
System.out.println();
// shuffle 3
arrayShuffle(array);
listDataAdder(array, list);
System.out.println("The list after shuffle 3 : "
+ list.toString());
}
// Creating a data to add shuffled data of the array to
// the list
static void listDataAdder(Object[] arr,
LinkedList<Object> list)
{
// creating a ListIterator on the LinkedList
ListIterator<Object> it = list.listIterator();
// Traversing the LinkedList and setting all
// shuffled data of the array to the list
for (Object e : arr) {
it.next();
it.set(e);
}
}
// creating a method to shuffle the array
static void arrayShuffle(Object[] arr)
{
Random rand = new Random();
for (int i = 0; i < arr.length - 1; i++) {
// select index randomly
int index = rand.nextInt(i + 1);
// swapping between i th term and the index th
// term
Object g = arr[index];
arr[index] = arr[i];
arr[i] = g;
}
}
}
|
Approach 2(Using Collections.shuffle(list))
- Create a LinkedList.
- Shuffle the elements of the list by using the shuffle() method of the Collections class.
Declaration
Syntax
Collections.shuffle(list);Exception: This method throws UnsupportedOperationException if the given list or its list-iterator does not support the set operation.
Example:
import java.util.Collections;
import java.util.LinkedList;
public class GFG {
public static void main(String args[])
{
// Creating a LinkedList
LinkedList<Object> list = new LinkedList<>();
list.add(45);
list.add("GFG");
list.add(2.56f);
list.add(965.321);
list.add('A');
list.add(true);
System.out.println(
"The LinkedList before shuffle : "
+ list.toString());
System.out.println();
// here we are shuffling more than once
// shuffle 1
Collections.shuffle(list);
System.out.println(
"The LinkedList after shuffle 1 : "
+ list.toString());
System.out.println();
// shuffle 2
Collections.shuffle(list);
System.out.println(
"The LinkedList after shuffle 2 : "
+ list.toString());
System.out.println();
// shuffle 3
Collections.shuffle(list);
System.out.println(
"The LinkedList after shuffle 3 : "
+ list.toString());
}
}
|
Example:
package com.w3spoint; 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); } } |
package com.w3spoint; 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); } }
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 outHow to reverse a LinkedList in Java.
Leave a Reply Cancel reply
Your email address will not be published. Required fields are marked *
Comment *
Name *
Email *
Please enable JavaScript to submit this form.Java Collections shuffle() Method
The shuffle() is a Java Collections class method which works by randomly permuting the specified list elements. There is two different types of Java shuffle() method which can be differentiated depending on its parameter. These are:
- Java Collections shuffle(list) Method
- Java Collections shuffle(list, random) Method
ShuffleUtil Class
import java.lang.reflect.Array; import java.util.*; public class ShuffleUtil { private static final int[] EMPTY_INT_ARRAY = new int[0]; private static final int SHUFFLE_THRESHOLD = 5; private static Random rand;Main Method
public static void main(String[] args) { List list = null; Integer[] arr = null; int[] iarr = null; long start = 0; int cycles = 1000; int n = 1000; // Shuffle List start = System.nanoTime(); list = range(n); for (int i = 0; i < cycles; i++) { ShuffleUtil.shuffle(list); } System.out.printf("%22s: %dns%n", "List Shuffle", (System.nanoTime() - start) / cycles); // Shuffle Integer[] start = System.nanoTime(); arr = toArray(list); for (int i = 0; i < cycles; i++) { ShuffleUtil.shuffle(arr); } System.out.printf("%22s: %dns%n", "Integer[] Shuffle", (System.nanoTime() - start) / cycles); // Shuffle int[] start = System.nanoTime(); iarr = toPrimitive(arr); for (int i = 0; i < cycles; i++) { ShuffleUtil.shuffle(iarr); } System.out.printf("%22s: %dns%n", "int[] Shuffle", (System.nanoTime() - start) / cycles); }How to Randomize or Shuffle a List in Java? Example
You can shuffle the list of any object but shuffling a sorted list of numbers makes it easy to understand by just looking at the result. In this program, I have first created a list of some integers and initialized it at the same time by using our ArrayList one-line initialization tip.Once you got the list of integers, we have passed that list to theCollections.shuffle() method for shuffling. It doesn't return anything but shuffles objects contained in the list.