Java Collection How to - Use Random Numbers to Draw name from an array








Question

We would like to know how to use Random Numbers to Draw name from an array.

Answer

import java.util.ArrayList;
/*from  ww w .  j a  va 2  s .  c  o m*/
public class Main{

    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        list.add("A");
        list.add("B");
        list.add("C");
        list.add("D");
        list.add("E");
        list.add("F");
        list.add("G");
        list.add("H");
        
        System.out.println(list);
        
        
        while (!list.isEmpty()) {
            long index = Math.round(Math.floor(Math.random() * list.size()));
            System.out.println("Name " + list.get((int) index));
            list.remove((int) index);
        }
        
    }
}

The code above generates the following result.