fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. Map<String,Integer> quantas = new HashMap<String,Integer>();
  13. quantas.put("a", 10);
  14. quantas.put("b", 20);
  15. quantas.put("c", 30);
  16. quantas.put("d", 15);
  17. quantas.put("e", 25);
  18. quantas.put("f", 5);
  19.  
  20. Comparator<Map.Entry<String,Integer>> comp = new Comparator<Map.Entry<String,Integer>>() {
  21. public int compare(Map.Entry<String,Integer> a, Map.Entry<String,Integer> b) {
  22. return a.getValue() < b.getValue() ? -1 :
  23. a.getValue() > b.getValue() ? 1 :
  24. a.getKey().compareTo(b.getKey()); // Desempate
  25. }
  26. };
  27.  
  28. PriorityQueue<Map.Entry<String,Integer>> fila =
  29. new PriorityQueue<Map.Entry<String,Integer>>(4, comp);
  30.  
  31. for ( Map.Entry<String,Integer> entry : quantas.entrySet() ) {
  32. fila.add(entry);
  33. if ( fila.size() > 3 )
  34. fila.poll(); // Remove o menor
  35. }
  36.  
  37. List<Map.Entry<String,Integer>> lista = new ArrayList<Map.Entry<String,Integer>>(fila);
  38. Collections.sort(lista, comp);
  39. Collections.reverse(lista);
  40. System.out.println(lista);
  41. }
  42. }
Success #stdin #stdout 0.07s 380224KB
stdin
Standard input is empty
stdout
[c=30, e=25, b=20]