[ACCEPTED]-Get max key of Map<K,V> using lambda-java-8

Accepted answer
Score: 14

The interface Stream contains the method max to get 5 the maximum element. You can use a method 4 reference as Comparator. The method max returns an Optional<Float>, because 3 there is no maximum element in an empty 2 stream. You can use the method orElse to provide 1 an alternative value for this case.

float max = map.keySet().stream().max(Float::compareTo).orElse(0.0f);
Score: 14

There's a more direct solution than operating 6 on the keySet(); operate directly on the 5 entrySet() using the comparator factories 4 added to Map.Entry.

Map.Entry<K,V> maxElt = map.entrySet().stream()

This permits not only getting 3 min/max elements, but also sorting, so its 2 easy to find the top ten key/value pairs 1 like this:

Stream<Map.Entry<K,V>> topTen = map.entrySet().stream()

More Related questions