Write a java program to shuffle the elements in a linked list.

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

Java




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;
}
}
}
Output The list before shuffle : [45, GFG, 2.56, 965.321, A, true] The list after shuffle 1 : [965.321, 2.56, GFG, 45, A, true] The list after shuffle 2 : [965.321, 45, A, 2.56, GFG, true] The list after shuffle 3 : [965.321, 45, GFG, 2.56, A, true]

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

public static void shuffle(List<?> list)

Syntax

Collections.shuffle(list);

Exception: This method throws UnsupportedOperationException if the given list or its list-iterator does not support the set operation.

Example:

Java




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());
}
}
Output The LinkedList before shuffle : [45, GFG, 2.56, 965.321, A, true] The LinkedList after shuffle 1 : [965.321, 2.56, true, 45, GFG, A] The LinkedList after shuffle 2 : [2.56, A, true, 45, GFG, 965.321] The LinkedList after shuffle 3 : [GFG, A, 965.321, 45, true, 2.56]




Article Tags :
Java
Java Programs
Technical Scripter
java-LinkedList
Technical Scripter 2020
Practice Tags :
Java
Read Full Article

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

By Ayush Sanghavi

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:

  1. Java Collections shuffle(list) Method
  2. 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.

You can print the list before and after calling to Collections.shuffle() method to see the effect of shuffling.

Here is our sample Java program to randomize a list of Integers:

import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Random; /** * Java Program to shuffle elements of a List. * Collections.shuffle() is used for shuffling. * * @author WINDOWS 8 */ public class RandomizeList { public static void main(String args[]) { List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7); System.out.println("list before shuffling : " + numbers); // shuffling the list Collections.shuffle(numbers); System.out.println("list after shuffling : " + numbers); // You can even provide your own Random instance // for randomizing data Collections.shuffle(numbers, new Random(System.nanoTime())); System.out.println("list after shuffling again : " + numbers); } } Output list before shuffling : [1, 2, 3, 4, 5, 6, 7] list after shuffling : [4, 7, 1, 5, 3, 2, 6] list after shuffling again : [5, 2, 7, 3, 1, 6, 4]

You can see that before shuffling numbers are in the same order they were inserted into the list but after shuffling they are in some random order. We shuffle again with our instance of the Random class which again changed the order of elements inside the list.

If you are interested to learn more about shuffling collections, you can also check these Java Collections and Stream API courses from Udemy, Coursera, and Pluralsight,one of the most comprehensive courses on Java Collection Framework.




Important Points about shuffling a List in Java

Here are some worth noting points about using theCollections.shuffle() method for shuffling list in Java :

1. Collections class provides overloaded shuffle() method, one uses default randomness while you can provide a Random object to other shuffle methods.

2. List implementations that don't implement the RandomAccess interface, this method first converts them to an array, shuffles them, and converts them back to the list to avoid O(n^2) performance.


That's all about how to randomize objects stored in a list in Java. You can use any of those two versions of shuffle() methods to shuffle a list of objects. There is no requirement that an object should implement Comparable or anything, you can basically shuffle the list of any object in Java.


Further Learning
How to sort an ArrayList in Java 8
How to remove duplicate elements from List in Java 8
How to sort a Map by keys in Java 8


Thanks for reading this tutorial so far. If you like this tutorial then please share it with your friends and colleagues. If you have any questions or feedback then please drop a note.

Collection Operations

The operations inherited from Collection all do about what you'd expect them to do, assuming you're already familiar with them. If you're not familiar with them from Collection, now would be a good time to read The Collection Interface section. The remove operation always removes the first occurrence of the specified element from the list. The add and addAll operations always append the new element(s) to the end of the list. Thus, the following idiom concatenates one list to another.

Here's a nondestructive form of this idiom, which produces a third List consisting of the second list appended to the first.

List list3 = new ArrayList(list1); list3.addAll(list2);

Note that the idiom, in its nondestructive form, takes advantage of ArrayList's standard conversion constructor.

And here's an example (JDK 8 and later) that aggregates some names into a List:

List list = people.stream() .map(Person::getName) .collect(Collectors.toList());

Like the Set interface, List strengthens the requirements on the equals and hashCode methods so that two List objects can be compared for logical equality without regard to their implementation classes. Two List objects are equal if they contain the same elements in the same order.

Video liên quan

Postingan terbaru

LIHAT SEMUA