fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6. import java.util.stream.*;
  7.  
  8. /* Name of the class has to be "Main" only if the class is public. */
  9. class Ideone
  10. {
  11. public static void main (String[] args) throws java.lang.Exception
  12. {
  13. Map<String, Double> map = new HashMap<String, Double>() {{
  14. put("A", 0.0);
  15. put("B", 3.14);
  16. put("C", 3.14);
  17. put("D", 8.8);
  18. put("E", 2.1);
  19. put("F", 1.01);
  20. }};
  21. System.out.println("answer= " + getTopN(map, 3).toString());
  22. }
  23.  
  24. static List<String> getTopN(Map<String, Double> map, int n) {
  25.  
  26. TreeSet<Map.Entry<String, Double>> topN = new TreeSet<>(
  27. Map.Entry.<String, Double>comparingByValue()
  28. .reversed() // by value descending, then by key
  29. .thenComparing(Map.Entry::getKey)); // to allow entries with repeated values
  30.  
  31. map.entrySet().forEach(e -> {
  32. topN.add(e);
  33. if (topN.size() > n) topN.pollLast();
  34. });
  35.  
  36. return topN.stream()
  37. .map(Map.Entry::getKey)
  38. .collect(Collectors.toList());
  39. }
  40. }
Success #stdin #stdout 0.2s 2184192KB
stdin
Standard input is empty
stdout
answer= [D, B, C]