Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Shuffle an Array Using List in Java



In this article, we will learn how to shuffle an array using a list in Java. Shuffling an array means randomly rearranging its elements. The Java Collections framework provides the Collections.shuffle() method, which can be used to shuffle a list in place.

What is an array in Java?

An array is a collection of elements of the same type, stored in contiguous memory locations.

What is a list in Java?

A List is an ordered collection (sequence) of elements in Java. It allows duplicates and maintains the order of insertion.

Shuffling an array using a list

The following are the steps to shuffle an array using a list ?

  • Step 1. Define the string array ? Initialize the array with string values: String str[] = {"A", "B", "C", "D", "E"};
String str[] = {"A", "B", "C", "D", "E"};
  • Step 2. Convert the array to a list ? Convert the array to a list using Arrays.asList()
List list = Arrays.asList(str);

  • Step 3. Shuffle the list  ?Shuffle the list using Collections.shuffle(list) and print.

Collections.shuffle(list);
System.out.println("Shuffled the array using List = " + list.toString());

Java program to shuffle an array using a list

Below is the program to shuffle an array using a list ?

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Demo {
	public static void main(String[] args) {
		String str[] = {"A", "B", "C", "D", "E"};
		List<String>list = Arrays.asList(str);
		Collections.shuffle(list);
		System.out.println("Shuffled the array using List = "+list.toString());
	}
}

Output

Shuffled the array using List = [C, B, E, D, A]

Updated on: 2024-11-23T03:57:11+05:30

193 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements