我有我需要排序的字符串列表(請參見下文)。比較和排序具有數字和特殊字符的字符串
- 「<5公頃」
- 「> = 10 ha至<20公頃」
- 「> = 20 ha至<50公頃」
- 「> = 5 ha至<10公頃」
- 「> = 50哈」
看起來簡單,但到現在爲止,我沒有找到一個簡單的方法來做到這一點。 Element類只有一個String類型的名爲code的屬性。 Java代碼就在下面,有什麼想法?
public class SortingListComparator {
private static List<Element> testList;
public static void main(String[] args) {
initList();
Collections.sort(testList, new ElementComparator());
for (Element elem : testList) {
System.out.println("Code of element : " + elem.getCode());
}
}
private static void initList() {
testList = new ArrayList<Element>();
Element elem1 = new Element("< 5 ha");
Element elem2 = new Element(">= 10 ha to < 20 ha");
Element elem3 = new Element(">= 20 ha to < 50 ha");
Element elem4 = new Element(">= 5 ha to < 10 ha");
Element elem5 = new Element(">= 50 Ha");
testList.add(elem1);
testList.add(elem2);
testList.add(elem3);
testList.add(elem4);
testList.add(elem5);
}
public static class ElementComparator implements Comparator<Element> {
@Override
public int compare(Element o1, Element o2) {
return o1.getCode().compareTo(o2.getCode());
}
}
}
首先,我們必須提出規則來定義某個特定記錄是在前一個還是後一個特定記錄之後進行的。 –
字符串「> = 5公頃到<10公頃」的記錄應該在值等於「<5公頃」(位於列表中的第二位) –