get top 3 entries based on values map java

http‮//:s‬www.lautturi.com
get top 3 entries based on values map java

To get the top 3 entries in a Map based on the values in Java, you can use the Stream API and the Entry.comparingByValue() method from the Map.Entry class. Here's an example of how you could do this:

import java.util.Map;
import java.util.stream.Stream;

Map<String, Integer> map = Map.of("A", 3, "B", 2, "C", 5, "D", 1, "E", 4);
Stream<Map.Entry<String, Integer>> stream = map.entrySet().stream();
stream.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
      .limit(3)
      .forEach(entry -> System.out.println(entry.getKey() + ": " + entry.getValue()));

This code will output the top 3 entries in the map based on the values, in descending order. For example, if the map contains the following entries:

A: 3
B: 2
C: 5
D: 1
E: 4

The code will output:

C: 5
E: 4
A: 3

Note that the Stream API is only available in Java 8 and later. If you are using an earlier version of Java, you will need to use a different approach to sort the entries in the map.

Created Time:2017-11-01 12:04:59  Author:lautturi