We can use shuffle() method which generates different order of output, to shuffle elements in an arraylist in java.
Syntax:
Collections.shuffle(arrayList);
Example:
package com.w3spoint; import java.util.ArrayList; import java.util.Collections; public class Test { public static void main(String args[]){ ArrayList<String> arrayList = new ArrayList<String>(); arrayList.add("Jai"); arrayList.add("Mahesh"); arrayList.add("Vivek"); arrayList.add("Naren"); arrayList.add("Hemant"); arrayList.add("Vishal"); System.out.println("Actual ArrayList:"+arrayList); Collections.shuffle(arrayList); System.out.println("Results after shuffle operation:" + arrayList); Collections.shuffle(arrayList); System.out.println("Results after shuffle operation:" + arrayList); } } |
Output
Actual ArrayList:[Jai, Mahesh, Vivek, Naren, Hemant, Vishal] Results after shuffle operation:[Naren, Vivek, Vishal, Mahesh, Hemant, Jai] Results after shuffle operation:[Vishal, Mahesh, Naren, Hemant, Jai, Vivek] |