Shuffle elements of ArrayList with Java Collections



In order to shuffle elements of ArrayList with Java Collections, we use the Collections.shuffle() method. The java.util.Collections.shuffle() method randomly permutes the list using a default source of randomness.

Declaration −The java.util.Collections.shuffle() method is declared as follows −

public static void shuffle(List <?> list)

Let us see a program to shuffle elements of ArrayList with Java Collections −

Example

 Live Demo

import java.util.*; public class Example {    public static void main (String[] args) {       ArrayList<Integer> list = new ArrayList<Integer>();       list.add(1);       list.add(2);       list.add(7);       list.add(8);       list.add(3);       list.add(9);       System.out.println("Original list : " + list);       Collections.shuffle(list); // shuffling the list       System.out.println("Shuffled list : " + list);    } }

Output

Original list : [1, 2, 7, 8, 3, 9] Shuffled list : [3, 8, 7, 9, 1, 2]
Updated on: 2020-06-25T14:32:41+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements