I have a list of Integer
List<Integer> lst = new ArrayList<>();
lst.add(10);
lst.add(15);
lst.add(16);
lst.add(8);
lst.add(100);
lst.add(1);
lst.add(40);
How to write a code so that I can get the top 5 max element from the list, namely 100, 40, 16, 15, 10
?
I have tried by using Java stream API:
Integer var = lst.stream().max(Integer::compare).get();
but get only one value element.
I have tried by using Java stream API, but get only one value,
Integer var = lst.stream().max(Integer::compare).get();
This will get you the max value of that list. To get the top 5 you have to do the following:
lst.stream()
.sorted(Comparator.reverseOrder())
.limit(5)
.collect(Collectors.toList());
The method sorted will sorted in ascending order, as one can read on:
sorted() Returns a stream consisting of the elements of this stream, sorted according to natural order.
However, we can use sorted(Comparator<? super T> comparator)
which:
Returns a stream consisting of the elements of this stream, sorted according to the provided Comparator.
Therefore you need to pass Comparator.reverseOrder() to sort in descending order. The limit(5)
will extract you the first 5 elements from the stream.
A more generic method:
private static void printTop(Collection<Integer> col, int top) {
List<Integer> collect = col.stream().sorted(Comparator.reverseOrder()).limit(top).collect(Collectors.toList());
System.out.println(collect);
}
A running example:
public static void main(String []args){
List<Integer> lst = List.of(10, 15, 16, 8, 100, 1, 40);
printTop(lst, 5);
}
private static void printTop(Collection<Integer> col, int top) {
List<Integer> collect = col.stream().sorted(Comparator.reverseOrder()).limit(top).collect(Collectors.toList());
System.out.println(collect);
}
Output:
[100, 40, 16, 15, 10]