Java – how to sort conditions using the flow API

I study stream API. I have this task I need to sort the list set according to their length order, and if several rows have the same length, 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

When you see the lines

Sony Xperia Z5
 ASUS Zenfone 3

And lines:

Meizu Pro 6 
    Heizu Pro 6

But my result must 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 length is the same, the sorting is alphabetical?

How do we collect results in list >? List < pair < string, long > for example:

String a = Abcd;
list.add(new Pair(a,a.length));

Solution

Add thenmatching() to the comparator chain to create an auxiliary sort order It will be applied when the primary sort is not enough:

phones.stream()
      .sorted(Comparator.comparingInt(String::length).reversed()
                        .thenComparing(Function.identity()))
      .forEach(System.out::println);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>