1

I'm trying to solve a challenge which requires you to reverse an int array in Java. The catch is that you only get one ;, so I'm assuming you need to use Streams API to do this.

I tried the conventional way, it reverses the array properly, but fails the one semicolon test -

  public static int[] reverse(int[] a) {
    List<Integer> numbers = IntStream.of(a).boxed().collect(Collectors.toList());
    Collections.reverse(numbers);
    return numbers.stream().mapToInt(i -> i).toArray();
  }

Next, I tried using Collections.reversedOrder() -

public static int[] reverse(int[] a) {
    return Arrays.stream(a).boxed()
     .sorted(Comparator.reverseOrder())
     .mapToInt(i -> i).toArray();
  }

However, since Collections.reversedOrder() impopses the reverse of the natural ordering of the elements in the collection, if the array consists of numbers 1 through 5, no matter what the order of elements in the array are, it will always return {5, 4, 3, 2, 1}.

There is a Comparator.reversed() method, but it needs to be called on an existing Comparator. I'm not sure how to do that, or if that would even work.

Is there another way to do this?

Manish Giri
  • 3,562
  • 8
  • 45
  • 81

1 Answers1

2

You can do it by inverting an index stream:

return IntStream.range(0, a.length)
        .map(i -> a[a.length - 1 - i])
        .toArray();
shmosel
  • 49,289
  • 6
  • 73
  • 138