How to shuffle a List in Java


First, create an Integer array −

Integer[] strArray = new Integer[] { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 };

Now, convert it into a List −

List<Integer>list = Arrays.asList(strArray);

Use Collections to shuffle as shown below −

Collections.shuffle(list);

Example

 Live Demo

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Demo {
   public static void main(String args[]) {
      Integer[] strArray = new Integer[] { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 };
      List<Integer>list = Arrays.asList(strArray);
      System.out.println("List = "+list);
      Collections.shuffle(list);
      System.out.println("Shuffled List = "+list);
   }
}

Output

List = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
Shuffled List = [100, 90, 40, 70, 20, 10, 80, 30, 60, 50]

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 30-Jul-2019

131 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements