Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fetch first 10 key value HashMap in Java

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 ?

like image 915
Fania Indah Avatar asked Apr 12 '26 13:04

Fania Indah


2 Answers

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:

  1. entrySet().steam() - take map's entry set, and make a stream of its values.
  2. map() - take the key value from the Map.Entry and pass it further down the stream
  3. sorted() - if the class implements Comparator interface it'll be used by default, or you can provide your own implementation as required.
  4. limit(10) - limit the numer of objects to 10.
  5. collect the sorted 10 values into a list.

sorted() method takes an optional Comparator parameter, where you can provide custom sorting logic if required.

like image 163
ttarczynski Avatar answered Apr 15 '26 03:04

ttarczynski


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));
like image 39
hsming Avatar answered Apr 15 '26 03:04

hsming