我有我需要排序的字符串列表(请参见下文)。比较和排序具有数字和特殊字符的字符串
- “<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公顷”(位于列表中的第二位) –