This is cool:
Map.Entry#comparingByKey and Map.Entry#comparingByValue. They both take another comparator or lambda that is used as a delegate for creating a Map.Entry comparator, that can be used to sort maps or find maximum and minimum pairs in a map by key or value like in the following example:
import java.time.LocalDate; import java.util.Map; import java.util.Random; import java.util.TreeMap; public class FindMaxMinInMaps { public static void main(String...a) { final Map<LocalDate, Integer> foobar = new TreeMap<>(); // Fill a date -> int map with 12 random ints between 0 and 100, new Random(System.currentTimeMillis()).ints(0,100).limit(12).forEach(value -> foobar.put( LocalDate.now().withMonth(foobar.size() + 1), value )); // print them for verbosity foobar.entrySet().forEach(System.out::println); // get the maximum Map.Entry<LocalDate, Integer> max = foobar // from all entries .entrySet() // stream them .stream() // max, obviously .max( // this one is cool. It generates // Map.Entry comparators by delegating to another // comparator, exists also for keys Map.Entry.comparingByValue(Integer::compareTo) ) // Get the optional (optional because the map can be empty) .get(); System.out.println("Max is " + max); } } |
2 comments
Saved my day
Thanks
want to explore more in Java8
Post a Comment