Java - Sort a list of objects that includes a special character

Strobe_ :

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.

But using the below code.

Collections.sort(myList);

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?

How would I implement this?

Tim Biegeleisen :

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.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=396270&siteId=1