2011-05-06 40 views

Respuesta

93

Básicamente, debe iterar sobre el conjunto de entradas del mapa, recordando tanto el "máximo conocido actualmente" como la clave asociada a él. (O simplemente el registro que contiene ambos, por supuesto.)

Por ejemplo:

Map.Entry<Foo, Bar> maxEntry = null; 

for (Map.Entry<Foo, Bar> entry : map.entrySet()) 
{ 
    if (maxEntry == null || entry.getValue().compareTo(maxEntry.getValue()) > 0) 
    { 
     maxEntry = entry; 
    } 
} 
+25

+1: puede tener más de una clave con el mismo valor máximo. Este ciclo te dará el primero que encuentre. –

+0

@ Peter: Buen punto :) –

+17

Cambiar> 0 a> = 0 le dará la última que encuentre –

36

Este código imprimirá todas las llaves con el valor máximo

public class NewClass4 { 
    public static void main(String[] args) 
    { 
     HashMap<Integer,Integer>map=new HashMap<Integer, Integer>(); 
     map.put(1, 50); 
     map.put(2, 60); 
     map.put(3, 30); 
     map.put(4, 60); 
     map.put(5, 60); 
     int maxValueInMap=(Collections.max(map.values())); // This will return max value in the Hashmap 
     for (Entry<Integer, Integer> entry : map.entrySet()) { // Itrate through hashmap 
      if (entry.getValue()==maxValueInMap) { 
       System.out.println(entry.getKey());  // Print the key with max value 
      } 
     } 

    } 
} 
6

Así es como lo hagas directamente (sin un bucle extra explícito) al definir el Comparator apropiado:

int keyOfMaxValue = Collections.max(
         yourMap.entrySet(), 
         new Comparator<Entry<Double,Integer>>(){ 
          @Override 
          public int compare(Entry<Integer, Integer> o1, Entry<Integer, Integer> o2) { 
           return o1.getValue() > o2.getValue()? 1:-1; 
          } 
         }).getKey(); 
50

Para completar, aquí es una manera de Java 8 de hacerlo

countMap.entrySet().stream().max((entry1, entry2) -> entry1.getValue() > entry2.getValue() ? 1 : -1).get().getKey(); 

o

Collections.max(countMap.entrySet(), (entry1, entry2) -> entry1.getValue() - entry2.getValue()).getKey(); 

o

Collections.max(countMap.entrySet(), Comparator.comparingInt(Map.Entry::getValue)).getKey(); 
+1

' (entry1, entry2) -> entry1.getValue() - entry2 .getValue() 'es más compacto para el comparador – JustABit

+0

mejora pequeña (y obvia) agradable. Gracias @Nyx – Hilikus

+3

¿Qué hacer si quiero todas las teclas que coinciden con el valor máximo? – Mouna

0

Para mi proyecto, he usado una versión ligeramente modificada de la de Jon y fátha de solución. En el caso de múltiples entradas con el mismo valor, devuelve la última entrada que encuentre:

public static Entry<String, Integer> getMaxEntry(Map<String, Integer> map) {   
    Entry<String, Integer> maxEntry = null; 
    Integer max = Collections.max(map.values()); 

    for(Entry<String, Integer> entry : map.entrySet()) { 
     Integer value = entry.getValue(); 

     if(null != value && max == value) { 
      maxEntry = entry; 
     } 
    } 

    return maxEntry; 
} 
1

¿Es esta solución bien?

int[] a = { 1, 2, 3, 4, 5, 6, 7, 7, 7, 7 }; 
Map<Integer, Integer> map = new HashMap<Integer, Integer>(); 
for (int i : a) { 
Integer count = map.get(i); 
map.put(i, count != null ? count + 1 : 0); 
} 
Integer max = Collections.max(map.keySet()); 
System.out.println(max); 
System.out.println(map); 
-1

usted puede hacer como que

HashMap<Integer,Integer> hm = new HashMap<Integer,Integer>(); 
hm.put(1,10); 
hm.put(2,45); 
hm.put(3,100); 
Iterator<Integer> it = hm.keySet().iterator(); 
Integer fk = it.next(); 
Integer max = hm.get(fk); 
while(it.hasNext()) { 
    Integer k = it.next(); 
    Integer val = hm.get(k); 
    if (val > max){ 
     max = val; 
     fk=k; 
    } 
} 
System.out.println("Max Value "+max+" is associated with "+fk+" key"); 
23

Un simple un trazador de líneas utilizando Java-8

Key key = Collections.max(map.entrySet(), Map.Entry.comparingByValue()).getKey(); 
+1

no funciona, método getKey() no encontrado – Samir

+3

@Samir https://docs.oracle.com/javase/ 7/docs/api/java /util/Map.Entry.html#getKey() –

+2

La solución más elegante y minimalista. Gracias –

4

Una respuesta que devuelve un opcional ya que el mapa puede no tener valor máximo si está vacío: map.entrySet().stream().max(Map.Entry.comparingByValue()).map(Map.Entry::getKey);

3

Java 8 forma de obtener todas las claves con valor máximo.

Integer max = PROVIDED_MAP.entrySet() 
      .stream() 
      .max((entry1, entry2) -> entry1.getValue() > entry2.getValue() ? 1 : -1) 
      .get() 
      .getValue(); 

List listOfMax = PROVIDED_MAP.entrySet() 
      .stream() 
      .filter(entry -> entry.getValue() == max) 
      .map(Map.Entry::getKey) 
      .collect(Collectors.toList()); 

System.out.println(listOfMax); 

También se puede paralelizar mediante el uso de parallelStream() en lugar de stream()

2

Tengo dos métodos, el uso de este método para obtener la clave con el valor máximo:

public static Entry<String, Integer> getMaxEntry(Map<String, Integer> map){   
    Entry<String, Integer> maxEntry = null; 
    Integer max = Collections.max(map.values()); 

    for(Entry<String, Integer> entry : map.entrySet()) { 
     Integer value = entry.getValue(); 
     if(null != value && max == value) { 
      maxEntry = entry; 
     } 
    } 
    return maxEntry; 
} 

Como ejemplo poniendo la Entrada con el valor máximo usando el método:

Map.Entry<String, Integer> maxEntry = getMaxEntry(map); 

Usando Java 8 podemos obtener un objeto que contiene el valor máximo:

Object maxEntry = Collections.max(map.entrySet(), Map.Entry.comparingByValue()).getKey();  

System.out.println("maxEntry = " + maxEntry); 
Cuestiones relacionadas