New methods in Map.Entry comparingByKey and comparingByValue

JDK 8 is still new and hot. I have explored some new methods in Map.Entry interface, to sort objects.

Image that we have following collection:

Initial data
1
2
3
4
5
Map map = new HashMap<>();
map.put("Kawasaki", 3);
map.put("Honda", 1);
map.put("Norton", 5);
map.put("Moto Guzzi", 2);

There are four new methods:

  • comparingByKey()
  • comparingByKey(Comparator<? super K> cmp)
  • comparingByValue()
  • comparingByValue(Comparator<? super K> cmp)

The method names are self-describing. If we pass different comparator, we can get different behaviour.

Comparing by value

If we want to sort by value with default behaviour (ascending), we can do something like this:

ComparingByValue
1
2
3
4
5
6
7
List<Map.Entry<String, Integer>> comparingByValue = map
.entrySet()
.stream()
.sorted(Map.Entry.comparingByValue())
.collect(Collectors.toList());

comparingByValue.forEach(System.out::println);

As a result, we get a list sorted by values:

1
2
3
4
Honda=1
Moto Guzzi=2
Kawasaki=3
Norton=5

Comparing by key

If we want to sort by key with default behaviour (ascending), we can do something like this:

ComparingByKey
1
2
3
4
5
6
7
List<Map.Entry<String, Integer>> comparingByKey = map
.entrySet()
.stream()
.sorted(Map.Entry.comparingByKey())
.collect(Collectors.toList());

comparingByKey.forEach(System.out::println);

As a result, we get a list sorted by keys alphabetically:

1
2
3
4
Honda=1
Kawasaki=3
Moto Guzzi=2
Norton=5

Comparing by key with comparator

If we want to sort by key length, we can pass function as a comparator,  Then we can achieve something like this:

ComparingByValue with comparator
1
2
3
4
5
6
7
List<Map.Entry<String, Integer>> comparingByValue = map
.entrySet()
.stream()
.sorted(Map.Entry.comparingByKey((String s1, String s2) -> s1.length() - s2.length()))
.collect(Collectors.toList());

comparingByValue.forEach(System.out::println);

As a result, we get a list sorted by keys length:

1
2
3
4
Honda=1
Norton=5
Kawasaki=3
Moto Guzzi=2

Photo credit

Comments