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?