Qual é a maneira mais fácil de obter a chave associada ao valor máximo em um mapa?
Acredito que Collections.max (someMap) retornará a chave max, quando você quiser a chave que corresponde ao valor máximo.
Basicamente, você precisaria fazer uma iteração no conjunto de inputs do mapa, lembrando tanto o “máximo conhecido atualmente” quanto a chave associada a ele. (Ou apenas a input contendo os dois, é claro).
Por exemplo:
Map.Entry maxEntry = null; for (Map.Entry entry : map.entrySet()) { if (maxEntry == null || entry.getValue().compareTo(maxEntry.getValue()) > 0) { maxEntry = entry; } }
Para completar, aqui está uma maneira do Java 8 de fazê-lo
countMap.entrySet().stream().max((entry1, entry2) -> entry1.getValue() > entry2.getValue() ? 1 : -1).get().getKey();
ou
Collections.max(countMap.entrySet(), (entry1, entry2) -> entry1.getValue() - entry2.getValue()).getKey();
ou
Collections.max(countMap.entrySet(), Comparator.comparingInt(Map.Entry::getValue)).getKey();
Este código irá imprimir todas as chaves com valor máximo
public class NewClass4 { public static void main(String[] args) { HashMapmap=new HashMap(); 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 entry : map.entrySet()) { // Itrate through hashmap if (entry.getValue()==maxValueInMap) { System.out.println(entry.getKey()); // Print the key with max value } } } }
Um simples liner usando o Java-8
Key key = Collections.max(map.entrySet(), Map.Entry.comparingByValue()).getKey();
Veja como fazer isso diretamente (sem um loop extra explícito) definindo o Comparator
apropriado:
int keyOfMaxValue = Collections.max( yourMap.entrySet(), new Comparator>(){ @Override public int compare(Entry o1, Entry o2) { return o1.getValue() > o2.getValue()? 1:-1; } }).getKey();
Uma resposta que retorna um Opcional, já que o mapa pode não ter valor máximo se estiver vazio: map.entrySet().stream().max(Map.Entry.comparingByValue()).map(Map.Entry::getKey);
Java 8 maneira de obter todas as chaves com 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);
Além disso, você pode fazer o paralelismo usando parallelStream()
vez de stream()
Eu tenho dois methods, usando este método para obter a chave com o valor máximo:
public static Entry getMaxEntry(Map map){ Entry maxEntry = null; Integer max = Collections.max(map.values()); for(Entry entry : map.entrySet()) { Integer value = entry.getValue(); if(null != value && max == value) { maxEntry = entry; } } return maxEntry; }
Como exemplo, obtendo a input com o valor máximo usando o método:
Map.Entry maxEntry = getMaxEntry(map);
Usando o Java 8 , podemos obter um object contendo o valor máximo:
Object maxEntry = Collections.max(map.entrySet(), Map.Entry.comparingByValue()).getKey(); System.out.println("maxEntry = " + maxEntry);
Esta solução está ok?
int[] a = { 1, 2, 3, 4, 5, 6, 7, 7, 7, 7 }; Map map = new HashMap(); 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);
Para o meu projeto, usei uma versão ligeiramente modificada da solução de Jon e Fathah. No caso de várias inputs com o mesmo valor, ele retorna a última input encontrada:
public static Entry getMaxEntry(Map map) { Entry maxEntry = null; Integer max = Collections.max(map.values()); for(Entry entry : map.entrySet()) { Integer value = entry.getValue(); if(null != value && max == value) { maxEntry = entry; } } return maxEntry; }
você pode fazer assim
HashMap hm = new HashMap(); hm.put(1,10); hm.put(2,45); hm.put(3,100); Iterator 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");