I'm reading in numbers from a .txt file using BufferedReader
. I want to reverse the order of elements in this steam so that when they are collected they will be arranged from the highest to the lowest. I don't want to sort after the array has been built because I have no idea how many elements might be in it, I only need the highest N elements.
in = new BufferedReader(reader);
int[] arr = in.lines()
.mapToInt(Integer::parseInt)
.sorted()
.limit((long) N)
.toArray();
Collect and Reverse a List in Java. The first approach would be to collect() the stream into a list - and then use the Collections. reverse() method on the list, which reverses it in-place. Note: If you also want to sort the collection while reversing it, you can use the sorted(Comparator.
Try negating the values before sorting and negating (back to normal) after sorting:
in = new BufferedReader(reader);
int[] arr = in.lines()
.mapToInt(Integer::parseInt)
.map(i -> -i).sorted().map(i -> -i)
.limit((long) N)
.toArray();
Because the reverse order is not the natural order, sorted()
can't be used to sort in reverse order. If you avoid the IntStream
, using a Stream<Integer>
instead, then you can use a Collections.reverseOrder()
to sort the stream in a reverse to the natural order. Then you can call mapToInt
and convert to int[]
at the end.
int[] arr = in.lines()
.map(Integer::valueOf) // Extract Integer, not int
.sorted(Collections.reverseOrder()) // On Stream<Integer>
.limit(N)
.mapToInt(i -> i) // map Integer to int
.toArray();
when using Instream, you are actually dealing with primitive, and your hands are tight (you are limited to natural ordering and you can't define custom comparator. You have two solutions:
stick with the primitive stream and come up with hacks like the one proposed by @normanrz
or you can convert to Integer (box) and use variety of solution like the one bellow (but be advised this boxing and unboxing might cause performance problems).
int[] sortedArray = IntStream.of(costs).boxed()
.sorted(Collections.reverseOrder())
.mapToInt(value -> value.intValue()).toArray();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With