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();
Because the reverse order is not the natural order,
sorted()can't be used to sort in reverse order. If you avoid theIntStream, using aStream<Integer>instead, then you can use aCollections.reverseOrder()to sort the stream in a reverse to the natural order. Then you can callmapToIntand convert toint[]at the end.