Image that we have following collection:
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.
If we want to sort by value with default behaviour (ascending), we can do something like this:
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:
Honda=1
Moto Guzzi=2
Kawasaki=3
Norton=5
If we want to sort by key with default behaviour (ascending), we can do something like this:
List<Map.Entry<String, Integer>> comparingByValue = map.entrySet().stream().sorted(Map.Entry.comparingByKey()).collect(Collectors.toList());
comparingByValue.forEach(System.out::println);
As a result, we get a list sorted by keys alphabetically:
Honda=1
Kawasaki=3
Moto Guzzi=2
Norton=5
If we want to sort by key length, we can pass function as a comparator, Then we can achieve something like this:
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:
Honda=1
Norton=5
Kawasaki=3
Moto Guzzi=2
No comments:
Post a Comment