0

I have this function.

public static int[] createArray(){
    int[] array = new int[5];
    array = {5, 6, 8, 10, 0};
    Collections.shuffle(Arrays.asList(array));
    return array;
}

It seems I can't get the array randomized by collection directly. How can I randomize and return the array properly?

Nooglers BIT
  • 71
  • 2
  • 11

2 Answers2

1

First collect the array to a List, then shuffle it and return the elements as an int[]. Something like,

public static int[] createArray() {
    int[] array = { 5, 6, 8, 10, 0 };
    List<Integer> al = IntStream.of(array).boxed().collect(Collectors.toList());
    Collections.shuffle(al);
    return al.stream().mapToInt(Integer::intValue).toArray();
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
1

You need to store a reference to the list before you shuffle and also note that Arrays.asList(array) will yield a List<int[]> which is not what you want.

Here is one way to go about it:

 static int[] createArray(){
      int[] array = {5, 6, 8, 10, 0};
      List<Integer> temp = Arrays.stream(array).boxed().collect(Collectors.toList());
      Collections.shuffle(temp);
      return temp.stream().mapToInt(Integer::intValue).toArray();
}
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126