简体   繁体   中英

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 ?

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.

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));

You need to use LinkedHashMap in order to retain the order of the elements (ie, insertion order) and you can refer the below code to retrieve the first 10 elements from the loaded map object:

Map<String, Integer> map = new LinkedHashMap<>();
//Load your values here
Set<String> keys = map.keySet();
String[] keysArray = keys.toArray(new String[keys.size()]);
for(int i=0; i<keysArray.length && i<10;i++) {
    System.out.println(map.get(keysArray[i]));
}

将地图的entrySet()取出到一个列表中,通过getValue()对其进行排序,并取值最大的 10 个条目。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM