i have hashmap like this:
{apple, 20}, {nanas,18}, {anggur, 12},...........
my hashmap already sorting descending by value. and i want to get 10 element from first element hashmap.
can anyone help me ?
If you use java 8, I would go with:
List<MyKeyType> keys = map.entrySet().stream()
.map(Map.Entry::getKey)
.sorted()
.limit(10)
.collect(Collectors.toList());
How it works:
sorted() method takes an optional Comparator parameter, where you can provide custom sorting logic if required.
Since your map already sorted, we can get first 10 key-values as a new map like this:
Map<String, Integer> res = map.entrySet().stream()
.limit(10)
.collect(Collectors.toMap(Entry::getKey, Entry::getValue));
If your map not sorted, we can go with:
Map<String, Integer> res = map.entrySet().stream()
.sorted((o1, o2) -> o2.getValue() - o1.getValue())
.limit(10)
.collect(Collectors.toMap(Entry::getKey, Entry::getValue));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With