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:
1 | Map map = new HashMap<>(); |
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:
1 | List<Map.Entry<String, Integer>> comparingByValue = map |
As a result, we get a list sorted by values:
1 | Honda=1 |
Comparing by key
If we want to sort by key with default behaviour (ascending), we can do something like this:
1 | List<Map.Entry<String, Integer>> comparingByKey = map |
As a result, we get a list sorted by keys alphabetically:
1 | Honda=1 |
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:
1 | List<Map.Entry<String, Integer>> comparingByValue = map |
As a result, we get a list sorted by keys length:
1 | Honda=1 |