Find min value in HashMap

Similar to how we found the maximum value in a map this example will show the opposite and find the minimum. To accomplish this we will compare each value finding the minimum value. In the setUp method mapValues will be initialized and populated to be used in each snippet below.

Setup

Map<Integer, Integer> mapOfValues;

@Before
public void setUp() {

    mapOfValues = new HashMap<Integer, Integer>();
    mapOfValues.put(4, 11);
    mapOfValues.put(5, 2);
    mapOfValues.put(6, 24);
    mapOfValues.put(7, 33);
    mapOfValues.put(8, 1);
}

Straight up Java

Until java 8 there isn't a great way found in the API using straight up java. Iterating over a hashmap and comparing each value and if it less than the prior it will be set to the minEntry temporary value.

@Test
public void min_value_map_java() {

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

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

        if (minEntry == null
                || entry.getValue().compareTo(minEntry.getValue()) < 0) {
            minEntry = entry;
        }
    }

    assertEquals(new Integer(1), minEntry.getValue());
}

Java 8

Transforming a hashmap to stream while passing the same comparator used to sort a map to the min method will return an java 8 Optional of type Entry. Getting the value should return an Integer with the value of 1.

@Test
public void min_value_hashmap_java8() {

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

    Optional<Entry<Integer, Integer>> minValue = mapOfValues.entrySet()
            .stream().min(valueComparator);

    assertEquals(new Integer(1), minValue.get().getValue());
}