1

I need to generate an array of integers in random order repeatedly in Java. I came up with the following ugly snippet (which runs in a bigger loop). What's a more efficient or compact way to do the same?

    ArrayList<Integer> t = new ArrayList<>();
    int[] d = new int[elts];
    for (int i = 0; i < elts; i++) {
        t.add(i);
    }
    Collections.shuffle(t);
    for (int i = 0; i < elts; i++) {
        d[i] = t.get(i);
    }
user2399453
  • 2,930
  • 5
  • 33
  • 60

3 Answers3

3

Use the Java 8 Stream API:

    List<Integer> list = IntStream.range(0, elts).boxed().collect(toList());
    Collections.shuffle(list);
    int[] d = list.stream().mapToInt(i -> i).toArray();
hoat4
  • 1,182
  • 12
  • 9
2

The same with Java 8 Stream API but using collectAndThen()

IntStream.range(0, elts).  // range from 0 to elts
      boxed().  // from int to Integer
      collect(collectingAndThen(toList(), integers -> { //collect to list  
          Collections.shuffle(integers);  //shuffle integer
          return integers.toArray(new Integer[integers.size()]); // convert list to array
      }));

and with StreamEx

    int[] ints = IntStreamEx.range(0, elts)
            .sorted((o1, o2) -> random.nextInt())
            .toArray();
Vlad Bochenin
  • 3,007
  • 1
  • 20
  • 33
1

Will work well in Java 8

List<Integer> range = IntStream.range(0, elts).boxed().collect(Collectors.toList());
Collections.shuffle(range);
Integer[] arr = new Integer[elts];
range.toArray(arr);
ares
  • 4,283
  • 6
  • 32
  • 63
  • Duplicate, the last two line can be merged, the question has int[] and not Integer[], and use zero sized arrays with toArray (https://shipilev.net/blog/2016/arrays-wisdom-ancients/). – hoat4 Jan 21 '17 at 07:52