Map
s are inherently unsorted. The fact that the first map is sorted is merely by chance. E.g.
Map<String, Integer> map1 = new HashMap<>();
map1.put("Four", 4);
map1.put("One", 1245598);
map1.put("two", 0);
map1.put("three", 1);
map1.put("Six", 6);
will result in
map1={Six=6, Four=4, One=1245598, two=0, three=1}
To get a sorted map, you need to use a special map type, such as TreeMap
. You can specify a comparator for TreeMap
, which allows you to sort the second Map
based on the values of the first map.
Map<String, Integer> map1 = new TreeMap<>();
map1.put("One", 1245598);
map1.put("two", 0);
map1.put("three", 1);
Map<String,Boolean> map2 = new TreeMap<>(Comparator.comparing(map1::get).reversed());
map2.put("One",true);
map2.put("two", false);
map2.put("three", true);
System.out.println("map1="+map1);
System.out.println("map2="+map2);
Output:
map1={One=1245598, three=1, two=0}
map2={One=true, three=true, two=false}
Note however that updates to the first map may break the second one.
Comparator.comparing(map1::get).reversed()
is just a short way to create a comparator in java 8:
Comparator.comparing(func)
Creates a Comparator
that compares 2 objects by comparing the results of applying func
to those objects, i.e. the value returned from the compare(o1, o2)
method of this Comparator
is
func.apply(o1).compareTo(func.apply(o2))
map1::get
is a method reference to the get
method of map1
. Given a value o1
it will return map1.get(o1)
. Combining those 2 facts the return type of the comparator created therefore is
map1.get(o1).compareTo(map1.get(o2))
comparator.reversed()
just returns a Comparator
for the reversed order for descending order instead of ascending sorting.