自定义排序方式,A排在a之前,B排在b之前 [英] Custom Sorting in way that A comes before a and B comes before b

查看:64
本文介绍了自定义排序方式,A排在a之前,B排在b之前的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的颜色列表:

I have a List of colors like this:

粉色,蓝色,红色,蓝色,灰色,绿色,紫色,黑色...等

Pink, Blue, Red, blue, Grey, green, purple, black ...etc

List<String> listOfColors =  Arrays.asList("Pink", "Blue", "Red", "blue", "Grey", "green", "purple", "black");

有一些中间操作,例如过滤一些水果色,现在剩下过滤结果要按顺序排序了:

There are some intermediate operation like filtering some fruit colors, now I am left with filtered results where I want them to be sorted in order:

蓝色,黑色,蓝色,灰色,绿色,粉红色,紫色,红色

Blue, black, blue, Grey, green, Pink, purple, Red

我尝试过:

List<String> collect = listOfColors.stream().sorted(String::compareToIgnoreCase)
        .collect(Collectors.toList());

它不能按预期方式工作.

It does not work as expected.

输出如下:

黑色,蓝色,蓝色,绿色,灰色,粉红色,紫色,红色

black, Blue, blue, green, Grey, Pink, purple, Red

我想要以下内容:

蓝色,黑色,蓝色,灰色,绿色,粉红色,紫色,红色

Blue, black, blue, Grey, green, Pink, purple, Red

推荐答案

我的解决方案是通过使用Comparator.thenComparing()方法分两步使用排序.

My solution is to use sorting in two steps by using the Comparator.thenComparing() method.

首先,仅将字符串与忽略大小写的第一个字符进行比较. 因此,具有相同第一个字符(无论大小写)的组到目前为止仍未排序.然后在第二步中,应用常规字母排序对未排序的子组进行排序.

First, compare the Strings only by the first character ignoring case. So the groups with the same first character (no matter what case) remain unsorted so far. Then in the second step apply the normal alphabetical sorting to sort those unsorted subgroups.

List<String> listOfColors =  Arrays.asList("Pink", "Blue", "Red", "blue", "Grey", "green", "purple", "black");
Comparator<String> comparator = Comparator.comparing(s -> 
        Character.toLowerCase(s.charAt(0)));
listOfColors.sort(comparator.thenComparing(Comparator.naturalOrder()));
System.out.println(listOfColors);

也许它仍然可以进行优化,但是可以达到预期的效果:

Maybe it can be still optimized, but it gives the desired result:

[Blue, black, blue, Grey, green, Pink, purple, Red]

这篇关于自定义排序方式,A排在a之前,B排在b之前的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆