How to shuffle the elements of a collection in Java



Problem Description

How to shuffle the elements of a collection?

Solution

Following example how to shuffle the elements of a collection with the help of Collections.shuffle() method of Collections class.

import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Main { public static void main(String[] argv) throws Exception { ArrayList<String> obj = new ArrayList<String>(); obj.add("A"); obj.add("E"); obj.add("I"); obj.add("O"); obj.add("U"); Collections.shuffle(obj); System.out.println(obj); } }

Result

The above code sample will produce the following result.

[I, U, A, O, E]
java_collections.htm
Advertisements