Mefisto_Fell :
I study the stream API, I have this task. I need to sort the List collection in the order of their length, if the lengths of several lines are the same, then sort them alphabetically.
My Code:
List<String> phones = new ArrayList<String>();
Collections.addAll(phones, "iPhone X", "Nokia 9", "Huawei Nexus 6P",
"Samsung Galaxy S8", "LG G6", "Xiaomi MI6", "Sony Xperia Z5",
"ASUS Zenfone 3", "Meizu Pro 6", "Heizu Pro 6",
"Pixel 2");
phones.stream().sorted(Comparator.comparingInt(String::length).reversed()).forEach(System.out::println);
I got this output:
Samsung Galaxy S8
Huawei Nexus 6P
Sony Xperia Z5
ASUS Zenfone 3
Meizu Pro 6
Heizu Pro 6
Xiaomi MI6
iPhone X
Nokia 9
Pixel 2
LG G6
As you see the lines
Sony Xperia Z5
ASUS Zenfone 3
And lines:
Meizu Pro 6
Heizu Pro 6
But my result have to be:
Samsung Galaxy S8
Huawei Nexus 6P
ASUS Zenfone 3
Sony Xperia Z5
Heizu Pro 6
Meizu Pro 6
Xiaomi MI6
iPhone X
Nokia 9
Pixel 2
LG G6
How can I improve my code so that if the lengths are the same, then the sorting is alphabetical?
How can we do collect results in List >? Where List <Pair <String, Long>
for example:
String a = Abcd;
list.add(new Pair(a, a.length));
Karol Dowbecki :
Add thenComparing()
to your comparator chain to create a secondary sort order. It will be applied when primary sort is not enough:
phones.stream()
.sorted(Comparator.comparingInt(String::length).reversed()
.thenComparing(Function.identity()))
.forEach(System.out::println);