IntStream may be a the easiest way but I can only pick up smallest M numbers as below:
public class Test {
private static final int[] arr = {5, 3, 4, 2, 9, 1, 7, 8, 6};
public static void main(String[] args) throws Exception {
System.out.println(Arrays.asList(IntStream.of(arr).sorted().limit(5).boxed().toArray()));
}
}
btw, considering algorithm complexity and assuming N >> M, a "sorted + limit" approach just have a complexity of O(N log(N)).
I think the best complexity may reach to O(N log(M)) but I do not know whether Java 8 has this kind of stream methods or collectors.
If you must use Streams:
Otherwise use a
PriorityQueue
and write yourself an invertingComparator
. Insertion will be O(N(log(N)) and removal of M elements will be O(M(log(N)). Not what you asked for, but maybe close enough.