mardi 31 octobre 2017

Select different random elements from an ArrayList of array of strings in java

I am Rookie. I have to select randomly different elements from an ArrayList which has an array of strings. I tried couple different ways but it is selecting the same array every time.Here are the ways I tried.

 public static void RandomSchedules(ArrayList<String[]> list)
{
    Random randomizer = new Random();
    for(int i=1; i<11; i++)
   {

    String[] random = list.get(new Random().nextInt(list.size()));
    System.out.println("Random Schedule " +  ":" + Arrays.toString(random));
    }
}

I also tried this in the above code.

   String[] random = list.get(randomizer.nextInt(list.size()));

But the result is same.

This is the other approach I have tried from Stack Overflow

 public static List<String[]> pickNRandom(ArrayList<String[]> lst, int n) {
List<String[]> copy = new LinkedList<String[]>(lst);
Collections.shuffle(copy);
return copy.subList(0, n);
 }

I am calling the above function as,

    List<String[]> randomPicks = pickNRandom(lst, 10);

Could anyone guide me how to get different elements.




Aucun commentaire:

Enregistrer un commentaire