So you know how to sort a Map
by value, maybe by reading this answer: Sort a Map by values (Java), where the Java 8 version of the answer is:
m1sorted = m1.entrySet()
.stream()
.sorted(Map.Entry.comparingByValue(Collections.reverseOrder()))
.collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(e1, e2) -> e1,
LinkedHashMap::new
));
So how do you sort m2
and m3
by the values of m1
?
Easy: You supply a Comparator
to sorted()
that compares the values, e.g.
.sorted(Comparator.comparing(e -> m1.get(e.getKey())).reversed())
You may have to explicitly specify the type of e
, since the inference engine may get lost: comparing((Entry<String, String> e) ->
If you don't like Comparator.comparing()
and reversed()
, and the inference issue, you can just use a lambda.
Here is all the code, as proof of concept:
Map<String, Integer> m1 = new HashMap<>();
m1.put("c1", 3);
m1.put("c2", 24);
m1.put("c3", 12);
Map<String, String> m2 = new HashMap<>();
m2.put("c1", "A");
m2.put("c2", "B");
m2.put("c3", "C");
Map<String, Double> m3 = new HashMap<>();
m3.put("c1", 3.4);
m3.put("c2", 4.6);
m3.put("c3", 12.3);
Map<String, Integer> m1s =
m1.entrySet()
.stream()
.sorted((e1, e2) -> Integer.compare(e2.getValue(), e1.getValue()))
.collect(Collectors.toMap(Map.Entry::getKey,
Map.Entry::getValue,
(e1, e2) -> e1,
LinkedHashMap::new));
Map<String, String> m2s =
m2.entrySet()
.stream()
.sorted((e1, e2) -> Integer.compare(m1.get(e2.getKey()), m1.get(e1.getKey())))
.collect(Collectors.toMap(Map.Entry::getKey,
Map.Entry::getValue,
(e1, e2) -> e1,
LinkedHashMap::new));
Map<String, Double> m3s =
m3.entrySet()
.stream()
.sorted((e1, e2) -> Integer.compare(m1.get(e2.getKey()), m1.get(e1.getKey())))
.collect(Collectors.toMap(Map.Entry::getKey,
Map.Entry::getValue,
(e1, e2) -> e1,
LinkedHashMap::new));
System.out.println(m1s);
System.out.println(m2s);
System.out.println(m3s);
Output
{c2=24, c3=12, c1=3}
{c2=B, c3=C, c1=A}
{c2=4.6, c3=12.3, c1=3.4}
Notice how e2
and e1
are reversed in the lambdas to cause descending order.
Of course, it would be much better to use the Object-Oriented features of Java and only have one Map
to objects with three fields for the values.