How to shuffle a List in Java

Java 8Object Oriented ProgrammingProgramming

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]
raja
Published on 24-Apr-2019 10:33:16
Advertisements