September 2019
Intermediate to advanced
816 pages
18h 47m
English
Once we create a Stream for a map, we can easily sort it by means of the Stream.sorted() method with or without a Comparator. This time, let's use a Comparator:
public static <K, V> Map<K, V> sortByKeyStream( Map<K, V> map, Comparator<? super K> c) { return map.entrySet() .stream() .sorted(Map.Entry.comparingByKey(c)) .collect(toMap(Map.Entry::getKey, Map.Entry::getValue, (v1, v2) -> v1, LinkedHashMap::new));}public static <K, V> Map<K, V> sortByValueStream( Map<K, V> map, Comparator<? super V> c) { return map.entrySet() .stream() .sorted(Map.Entry.comparingByValue(c)) .collect(toMap(Map.Entry::getKey, Map.Entry::getValue, (v1, v2) -> v1, LinkedHashMap::new));}
We need to rely on LinkedHashMap ...