How to fetch first 10 key value HashMap in Java

11,235

Solution 1

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.

Solution 2

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));
Share:
11,235
Fania Indah
Author by

Fania Indah

Updated on June 05, 2022

Comments

  • Fania Indah
    Fania Indah almost 2 years

    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 ?

  • Ole V.V.
    Ole V.V. about 7 years
    LinkedHashMap maintains insertion order or optionally access order — not descending order by value.
  • Ole V.V.
    Ole V.V. about 7 years
    So would I. :-)
  • testphreak
    testphreak almost 4 years
    Since the map already appears to be sorted, this can be simplified to a less verbose - List<String> keys = sortedMap.keySet().stream() .limit(10) .collect(Collectors.toList());