Find max value in HashMap

This sample code will show how to get the max value from a java map. To accomplish this we will compare each value finding the max value. In the setUp method mapValues will be initialized and populated to be used in each snippet below.

Setup

Map<Integer, Integer> mapValues;

@Before
public void setUp() {

    mapValues = new HashMap<Integer, Integer>();
    mapValues.put(1, 3);
    mapValues.put(2, 4);
    mapValues.put(3, 5);
    mapValues.put(4, 6);
    mapValues.put(5, 7);
}

Straight up Java

There isn't a great way using straight up java prior to java 8. Looping over a map and comparing each value and if it greater than the prior it will be set to the maxEntry temporary value.

@Test
public void max_value_map_java() {

    Map.Entry<Integer, Integer> maxEntry = null;

    for (Map.Entry<Integer, Integer> entry : mapValues.entrySet()) {

        if (maxEntry == null
                || entry.getValue().compareTo(maxEntry.getValue()) > 0) {
            maxEntry = entry;
        }
    }

    assertEquals(new Integer(7), maxEntry.getValue());
}

Java 8

Converting a stream from a hashmap while passing the same comparator used in how to sort a hashmap to the max method will return an java 8 Optional object of type Entry. Getting the value should return an Integer with the value of 7.

@Test
public void max_value_hashmap_java8() {

    Comparator<? super Entry<Integer, Integer>> maxValueComparator = (
            entry1, entry2) -> entry1.getValue().compareTo(
            entry2.getValue());

    Optional<Entry<Integer, Integer>> maxValue = mapValues.entrySet()
            .stream().max(maxValueComparator);

    assertEquals(new Integer(7), maxValue.get().getValue());
}