It is difficult to say whether .sorted().limit((long) N).toArray() will be optimized in some cases (its implementation depends, but taking into account the current Oracles implementation, I would not expect this), but in this particular case the stream The source is a stream of unknown size, which makes optimization even less likely.
If you want to be safe, you can adapt this solution to efficiently obtain n maximum stream numbers. All you have to do is reorder:
public static IntStream maxValuesDescending(IntStream source, int limit) { TreeMap<Integer,Integer> m=new TreeMap<>(Comparator.reverseOrder()); source.forEachOrdered(new IntConsumer() { int size, min=Integer.MIN_VALUE; public void accept(int value) { if(value<min) return; m.merge(value, 1, Integer::sum); if(size<limit) size++; else m.compute(min=m.lastKey(), (k,count)->count==1? null: count-1); } }); if(m.size()==limit)
Then you can use it as
int[] arr = maxValuesDescending(in.lines().mapToInt(Integer::parseInt), N).toArray();
But you do not need to create an array, as you can use arbitrary IntStream operations for the result. This solution will contain no more than N values, even less if there are duplicates, since it contains only certain values โโand their score.
source share