get Random element from a List - Java java.util

Java examples for java.util:List Element

Description

get Random element from a List

Demo Code


import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Random;
import edu.atilim.acma.util.Delegate.Func1P;

public class Main{
    public static void main(String[] argv){
        Collection collection = java.util.Arrays.asList("asdf","java2s.com");
        System.out.println(getRandom(collection));
    }//from w  ww. ja va 2  s  . com
    private static Random random = new Random();
    public static <T> T getRandom(Collection<T> collection) {
        List<T> list = new ArrayList<T>(collection);
        if (list.size() == 0)
            return null;
        return list.get(random.nextInt(list.size()));
    }
}

Related Tutorials