Finding a key associated with a maximum value on a Java map

What is the easiest way to get the key associated with the maximum value on the map?

I believe Collections.max (someMap) will return the maximum key if you need a key corresponding to the maximum value.

+122
java hashmap
May 6 '11 at 12:07
source share
15 answers

Basically, you will need to iterate over a set of map entries, remembering both the "currently known maximum" and the key associated with it. (Or just a record containing both, of course.)

For example:

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; } } 
+121
May 6 '11 at 12:10
source share

For completeness, here is the java-8 way to do it

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

or

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

or

 Collections.max(countMap.entrySet(), Comparator.comparingInt(Map.Entry::getValue)).getKey(); 
+93
Jan 18 '15 at 21:31
source share

This code will print all keys with the maximum value.

 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 } } } } 
+49
Jun 29 2018-12-12T00:
source share

Simple single liner using Java-8

 Key key = Collections.max(map.entrySet(), Map.Entry.comparingByValue()).getKey(); 
+39
May 22 '16 at 1:04
source share

Here's how to do it directly (without an explicit extra loop) by defining the appropriate Comparator :

 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(); 
+8
May 23 '14 at 17:09
source share

An answer that returns an optional parameter, since the map cannot have a maximum value if it is empty: map.entrySet().stream().max(Map.Entry.comparingByValue()).map(Map.Entry::getKey);

+6
Nov 09 '16 at 22:24
source share

Java 8 is a way to get all keys with maximum value.

 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); 

You can also parallelize it using parallelStream() instead of stream()

+4
Nov 09 '16 at 23:20
source share

I have two methods using this method to get the key with the maximum value:

  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; } 

As an example, enter Entry with the maximum value using the method:

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



Using Java 8 , we can get an object containing the maximum value:

 Object maxEntry = Collections.max(map.entrySet(), Map.Entry.comparingByValue()).getKey(); System.out.println("maxEntry = " + maxEntry); 
+4
Jun 22 '17 at 20:20
source share

1. Using Stream

 public <K, V extends Comparable<V>> V maxUsingStreamAndLambda(Map<K, V> map) { Optional<Entry<K, V>> maxEntry = map.entrySet() .stream() .max((Entry<K, V> e1, Entry<K, V> e2) -> e1.getValue() .compareTo(e2.getValue()) ); return maxEntry.get().getKey(); } 

2. Using Collections.max () with a lambda expression

  public <K, V extends Comparable<V>> V maxUsingCollectionsMaxAndLambda(Map<K, V> map) { Entry<K, V> maxEntry = Collections.max(map.entrySet(), (Entry<K, V> e1, Entry<K, V> e2) -> e1.getValue() .compareTo(e2.getValue())); return maxEntry.getKey(); } 

3. Using a stream with reference to a method

  public <K, V extends Comparable<V>> V maxUsingStreamAndMethodReference(Map<K, V> map) { Optional<Entry<K, V>> maxEntry = map.entrySet() .stream() .max(Comparator.comparing(Map.Entry::getValue)); return maxEntry.get() .getKey(); } 

4. Using Collections.max ()

  public <K, V extends Comparable<V>> V maxUsingCollectionsMax(Map<K, V> map) { Entry<K, V> maxEntry = Collections.max(map.entrySet(), new Comparator<Entry<K, V>>() { public int compare(Entry<K, V> e1, Entry<K, V> e2) { return e1.getValue() .compareTo(e2.getValue()); } }); return maxEntry.getKey(); } 

5. Using simple iteration

 public <K, V extends Comparable<V>> V maxUsingIteration(Map<K, V> map) { Map.Entry<K, V> maxEntry = null; for (Map.Entry<K, V> entry : map.entrySet()) { if (maxEntry == null || entry.getValue() .compareTo(maxEntry.getValue()) > 0) { maxEntry = entry; } } return maxEntry.getKey(); } 
+3
Jan 25 '19 at 14:32
source share

Is this solution ok?

 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); 
+2
Nov 18 '15 at 17:24
source share

For my project, I used a slightly modified version of the solution by Jon and Fathah. In the case of several records with the same value, the last record found is returned:

 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; } 
0
Sep 20 '15 at 2:44
source share
 int maxValue = 0; int mKey = 0; for(Integer key: map.keySet()){ if(map.get(key) > maxValue){ maxValue = map.get(key); mKey = key; } } System.out.println("Max Value " + maxValue + " is associated with " + mKey + " key"); 
0
Jun 04 '19 at 20:44 on
source share

Most element / maximum element on the map:

 public class Main { public static void main(String[] args) { int[] a = {1,3,4,3,4,3,2,3,3,3,3,3}; List<Integer> list = Arrays.stream(a).boxed().collect(Collectors.toList()); Map<Integer, Long> map = list.parallelStream() .collect(Collectors.groupingBy(Function.identity(),Collectors.counting())); System.out.println("Map => " + map); //{1=1, 2=1, 3=8, 4=2} map.entrySet() .stream() .max(Comparator.comparing(Entry::getValue))//compare the values and get the maximum value .map(Entry::getKey)// get the key appearing maximum number of times .ifPresentOrElse(System.out::println,() -> new RuntimeException("no such thing")); /* * OUTPUT : Map => {1=1, 2=1, 3=8, 4=2} * 3 */ // or in this way System.out.println("............."); Integer maxAppearedElement = map.entrySet() .parallelStream() .max(Comparator.comparing(Entry::getValue)) .map(Entry::getKey) .get(); System.out.println(maxAppearedElement); } } 
0
Jul 26 '19 at 11:25
source share

this card

HashMap abc = new HashMap & lt;> ();

get all records on the map with the maximum value.

You can use any of the methods below in the filter to get the corresponding entries on the map for sets of minimum or maximum values

 Collections.max(abc.values()) Collections.min(abc.values()) Collections.max(abc.keys()) Collections.max(abc.keys()) abc.entrySet().stream().filter(entry -> entry.getValue() == Collections.max(abc.values())) 

if you want to get the keys for the filter card

 abc.entrySet() .stream() .filter(entry -> entry.getValue() == Collections.max(abc.values())) .map(Map.Entry::getKey); 

if you want to get values ​​for the filtered map

 abc.entrySet() .stream() .filter(entry -> entry.getValue() == Collections.max(abc.values())) .map(Map.Entry::getvalue) 

if you want to get all such keys in the list:

 abc.entrySet() .stream() .filter(entry -> entry.getValue() == Collections.max(abc.values())) .map(Map.Entry::getKey) .collect(Collectors.toList()) 

if you want to get all such values ​​in the list:

 abc.entrySet() .stream() .filter(entry -> entry.getValue() == Collections.max(abc.values())) .map(Map.Entry::getvalue) .collect(Collectors.toList()) 
0
Aug 30 '19 at 6:57
source share

You can do it

 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"); 
-2
Apr 25 '16 at 8:11
source share



All Articles