Reputation: 279
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.
Upvotes: 1
Views: 9611
Reputation: 158
You can sort your List and then pop the last 5 elements or the first 5, depending on the way you've implemented the Comparable method.
Upvotes: 1
Reputation: 3728
get the 5 max-values in natural order
both works for list-size < 5 w/o exception
with a lambda (as OP wanted)
int[] n = {0};
List<Integer> rslt = lst.stream().sorted().dropWhile(
i -> n[0]++ < Math.max(0, lst.size() - 5) ).collect( toList() );
with collection methods
lst.sort( Integer::compare );
List<Integer> rslt = lst.subList( Math.max(0, lst.size() - 5), lst.size() );
Upvotes: 1
Reputation: 51453
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]
Upvotes: 7
Reputation: 307
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);
List<Integer> lst1 = lst.stream().sorted(Comparator.reverseOrder()).limit(5).collect(Collectors.toList());
System.out.println(lst1);
this can help you in getting the top 5 max elements.
Upvotes: 3