fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.util.stream.*;
  5. import java.lang.*;
  6. import java.io.*;
  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, Number> map = new HashMap<>();
  14. map.put("1", 1);
  15. map.put("3", 3);
  16. map.put("10", 10);
  17. map.put("5", 5);
  18. map.put("2", 2);
  19. map.put("4", 4);
  20. map.put("6", 6);
  21. map.put("8", 8);
  22. map.put("7", 7);
  23. map.put("9", 9);
  24.  
  25. Map<String, Number> topValues = getTopValuesDataMap(map, 5);
  26. System.out.println("Integers:");
  27. System.out.println(String.join(",", topValues.keySet()));
  28. System.out.println();
  29.  
  30. map.clear();
  31. map.put("1.1", 1.1f);
  32. map.put("1.3", 1.3f);
  33. map.put("1.9", 1.9f);
  34. map.put("1.5", 1.5f);
  35. map.put("1.6", 1.6f);
  36. map.put("1.2", 1.2f);
  37. map.put("1.4", 1.4f);
  38. map.put("1.8", 1.8f);
  39. map.put("1.7", 1.7f);
  40.  
  41. topValues = getTopValuesDataMap(map, 5);
  42. System.out.println("Floats:");
  43. System.out.println(String.join(",", topValues.keySet()));
  44. }
  45.  
  46. private static Map<String, Number> getTopValuesDataMap(Map<String, Number> chartDataMap, int limit) {
  47. return chartDataMap.entrySet().stream()
  48. .sorted(Map.Entry.comparingByValue(Comparator.comparing(Number::intValue).reversed())).limit(limit)
  49. .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
  50. (oldValue, newValue) -> oldValue, LinkedHashMap::new));
  51. }
  52. }
Success #stdin #stdout 0.09s 711680KB
stdin
Standard input is empty
stdout
Integers:
10,9,8,7,6

Floats:
1.1,1.2,1.3,1.4,1.5