我想按字母顺序对名称进行排序,但首先应该使用特殊字符。
从下面的代码特殊字符到最后,
Collections.sort(elementList,new Comparator<Element>() {
@Override
public int compare(Element o1, Element o2) {
return o1.getDisplayName().toUpperCase().compareTo(o2.getDisplayName().toUpperCase());
}
});
答案 0 :(得分:0)
以下程序有效。它在一开始就用特殊字符对字符串进行排序。
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
public class ComparatorDemo {
String element;
public ComparatorDemo(String element) {
this.element = element;
}
public static void main(String[] args) {
List<ComparatorDemo> stringCollection = new LinkedList<>();
stringCollection.add(new ComparatorDemo("abcd"));
stringCollection.add(new ComparatorDemo("jklm"));
stringCollection.add(new ComparatorDemo("opr"));
stringCollection.add(new ComparatorDemo("zabh"));
stringCollection.add(new ComparatorDemo("bhuy"));
stringCollection.add(new ComparatorDemo("@theh#saj"));
stringCollection.add(new ComparatorDemo("*&^%$"));
stringCollection.add(new ComparatorDemo("**"));
stringCollection.add(new ComparatorDemo("!@#"));
stringCollection.add(new ComparatorDemo("@@#$"));
stringCollection.add(new ComparatorDemo("#$%$"));
stringCollection.add(new ComparatorDemo("%^return"));
System.out.println(stringCollection);
Comparator<ComparatorDemo> comparator = new Comparator<ComparatorDemo>() {
@Override
public int compare(ComparatorDemo o1, ComparatorDemo o2) {
return o1.element.toUpperCase().compareTo(
o2.element.toUpperCase());
}
};
Collections.sort(stringCollection, comparator);
System.out.println(stringCollection);
}
@Override
public String toString() {
return "ComparatorDemo [element=" + element + "]";
}
}
Output :
Unsorted List - [ComparatorDemo [element=abcd], ComparatorDemo [element=jklm], ComparatorDemo [element=opr], ComparatorDemo [element=zabh], ComparatorDemo [element=bhuy], ComparatorDemo [element=@theh#saj], ComparatorDemo [element=*&^%$], ComparatorDemo [element=**], ComparatorDemo [element=!@#], ComparatorDemo [element=@@#$], ComparatorDemo [element=#$%$], ComparatorDemo [element=%^return]]
Sorted List - [ComparatorDemo [element=!@#], ComparatorDemo [element=#$%$], ComparatorDemo [element=%^return], ComparatorDemo [element=*&^%$], ComparatorDemo [element=**], ComparatorDemo [element=@@#$], ComparatorDemo [element=@theh#saj], ComparatorDemo [element=abcd], ComparatorDemo [element=bhuy], ComparatorDemo [element=jklm], ComparatorDemo [element=opr], ComparatorDemo [element=zabh]]