How to shuffle elements in ArrayList

shuffle an ArrayList in java means we can changes position of elements in random orders. In order to shuffle elements of ArrayList with Java Collections, we will use the Collections.shuffle() method and second way this write our own function for that. In this tutorial we use two method for shuffle an ArrayList

Method 1: Collections.shuffle() in Java with Examples

Syntax :

public static void shuffle(List<?> list) {
}

Let’s see this by code

import java.util.ArrayList;
import java.util.Collections;

public class Shuffle {

public static void main(String[] args) {
ArrayList<String> arr = new ArrayList<String>();
// add element in arraylist
arr.add("c");
arr.add("php");
arr.add("html");
arr.add("java");
// print arraylist
System.out.println("arrayList is = " + arr);

/*
* Randomly permutes the specified list using a default
source of randomness
*/

Collections.shuffle(arr);

for (String el : arr) {
System.out.println(el);
}

Collections.shuffle(arr);

System.out.println("Second Time shuffle");
for (String el : arr) {
System.out.println(el);
}

}
}

Output:

arrayList is = [c, php, html, java]

java
c
php
html

Second Time shuffle

php
java
html
c

Method 2: shuffle ArrayList without collections in Java

There we write our own function for shuffle ArrayList element

package com.demo.arraylist;

import java.util.ArrayList;
import java.util.Random;

public class ArrayListShuffle {
	
	public static void main(String[] args) {
		ArrayList<String> arr = new ArrayList<String>();
		// add element in arraylist
		arr.add("c");
		arr.add("php");
		arr.add("html");
		arr.add("java");
		// print arraylist
		System.out.println("before shuffle arrayList is = " + arr);
		
        Random r = new Random(); 
        
        for (int i = arr.size()-1; i > 0 ; i--) {
        	
        	//pick any random number 0 to i
			int j = r.nextInt(i);
			
			//swap element
			
			String temp = arr.get(i);
			arr.set( i,arr.get(j));
			arr.set(j, temp);
			
		}
        
        //print arraylist
       System.out.println("after shuffle arraylist is ="+ arr);
		
	}

}

Output :

before shuffle arrayList is = [c, php, html, java]
after shuffle arraylist is =[java, c, php, html]

Leave a Reply

Your email address will not be published. Required fields are marked *

− 3 = 2