Java-对包含特殊字符的对象列表进行排序 [英] Java - Sort a list of objects that includes a special character

查看:114
本文介绍了Java-对包含特殊字符的对象列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上我有一个像这样的对象的数组列表:

Basically i have an arraylist of objects like so:

[{name: 'A'}, {name: 'B'}, {name:'?'}]

我想对它们进行排序,以使问号位于上面的末尾.

I want to sort these so that the question mark is at the end like above.

但是使用下面的代码.

Collections.sort(myList);

这总是导致对象首先带有问号,我认为这是由于ASCII排序引起的吗?我认为正确的方法是使用比较器函数,但是我不确定用字母和特殊字符将其成形吗?

This always results in the object with the question mark first, I think this is due to ASCII ordering? I think the correct way forward is to use a comparator function but i'm not sure how that would take shape with letters and special characters?

我将如何实施?

推荐答案

在Java 8中,您可以使用两层的自定义比较器:

In Java 8, you may use a two-tiered custom comparator:

// given
List<YourObject> list;
list.sort((o1, o2) -> "?".equals(o1.getName()) ? 1 :
    ("?".equals(o2.getName()) ? -1 : o1.getName().compareTo(o2.getName())));

这里的排序逻辑是,如果一个或另一个名称是?,那么我们总是将最后一个?排序.如果两个名字都是?,或者都不是?,那么我们将使用默认的字典字符串排序方式进行排序.

The sorting logic here is that if one or the other names be ?, then we always sort that ? last. If both names be ?, or if neither be ?, then we sort using the default lexicographical string sorting.

这篇关于Java-对包含特殊字符的对象列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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