Shuffle Elements of ArrayList in Java
Last Updated :
07 Jan, 2021
Shuffling means changing the positions of ArrayList elements randomly. After shuffling, they will be in different order.
Following is the example of Shuffling ArrayList elements.
Ways to shuffle elements of ArrayList:
- Using Random class
- Using Collections.shuffle()
Method 1: Using Random class
- In this method we will be going to shuffle ArrayList element using Random class to generate random index.
- And java collections.swap() method to swap ArrayList elements.
- And one more algorithm we will be going to use that is Fisher–Yates shuffle.
Code:
Java
import java.util.*;
class ArraylistShuffle {
public static void main(String args[])
{
ArrayList<Integer> al = new ArrayList<Integer>();
al.add( 10 );
al.add( 20 );
al.add( 30 );
al.add( 40 );
al.add( 50 );
al.add( 60 );
al.add( 70 );
al.add( 80 );
System.out.println( "Before shuffling Arraylist:" );
Iterator itr = al.iterator();
while (itr.hasNext()) {
System.out.print(itr.next() + " " );
}
System.out.println( "" );
Random r1 = new Random();
for ( int i = al.size() - 1 ; i >= 1 ; i--) {
Collections.swap(al, i, r1.nextInt(i + 1 ));
}
System.out.println( "After shuffling Arraylist:" );
itr = al.iterator();
while (itr.hasNext()) {
System.out.print(itr.next() + " " );
}
}
}
|
Output
Before shuffling Arraylist:
10 20 30 40 50 60 70 80
After shuffling Arraylist:
10 60 30 20 50 80 40 70
Method 2: Using Collections.shuffle()
Shuffle ArrayList Elements by using Collections.shuffle().
Java
import java.util.*;
class ArraylistShuffle {
public static void main(String args[])
{
ArrayList<String> al = new ArrayList<String>();
al.add( "C" );
al.add( "C++" );
al.add( "Java" );
al.add( "Python" );
al.add( "PHP" );
al.add( "Javascript" );
System.out.println( "Before shuffling Arraylist:" );
Iterator itr = al.iterator();
while (itr.hasNext()) {
System.out.print(itr.next() + " " );
}
System.out.println( "" );
Collections.shuffle(al);
System.out.println( "After shuffling Arraylist:" );
itr = al.iterator();
while (itr.hasNext()) {
System.out.print(itr.next() + " " );
}
}
}
|
Output
Before shuffling Arraylist:
C C++ Java Python PHP Javascript
After shuffling Arraylist:
PHP Java C++ C Javascript Python
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...