Java 比较和排序具有数字和特殊字符的字符串

Java 比较和排序具有数字和特殊字符的字符串,java,Java,我有一个需要排序的字符串列表(见下文) “=10公顷到=20公顷到=5公顷到=50公顷” 看起来很简单,但直到现在,我还没有找到一个简单的方法。 元素类只有一个名为code的字符串类型的属性。 Java代码就在下面,你知道吗 public class SortingListComparator { private static List<Element> testList; public static void main(String[] arg

我有一个需要排序的字符串列表(见下文)

  • “<5公顷”
  • “>=10公顷到<20公顷”
  • “>=20公顷到<50公顷”
  • “>=5公顷到<10公顷”
  • “>=50公顷”
看起来很简单,但直到现在,我还没有找到一个简单的方法。 元素类只有一个名为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());
        }   
    }    
  }
公共类排序列表比较器{
私有静态列表testList;
公共静态void main(字符串[]args){
initList();
sort(testList,newelementcomparator());
for(元素元素:testList){
System.out.println(“元素代码:+elem.getCode());
}
}
私有静态void initList(){
testList=newarraylist();
元素elem1=新元素(<5公顷);
元素elem2=新元素(“>=10公顷至<20公顷”);
元素elem3=新元素(“>=20公顷至<50公顷”);
元素elem4=新元素(“>=5公顷至<10公顷”);
元素elem5=新元素(“>=50公顷”);
testList.add(elem1);
testList.add(elem2);
testList.add(elem3);
testList.add(elem4);
testList.add(elem5);
}
公共静态类ElementComparator实现Comparator{
@凌驾
公共整数比较(元素o1、元素o2){
返回o1.getCode().compareTo(o2.getCode());
}   
}    
}

您可以使用如下流:

testList = testList.stream()
    .sorted((one,another)->one.getCode().compareTo(another.getCode()))
    .collect(Collectors.toList());

这里真正的答案是:后退一步——创建有用的抽象

您不应该将问题视为“字符串”排序。您可以看到,这些字符串表示间隔(或范围)信息

意义:虽然它看起来像“更多的工作”,但是你应该考虑建模这些方面。换言之:

  • 创建一个表示(数学)间隔的类
  • 创建将类似“<5 ha”的字符串解析为interval对象的代码
  • 然后对间隔对象进行排序
除了创建自己的类之外,您还可以查看第三方库,如下所述


关键是:字符串包含非常特殊的信息。好的面向对象编程的整体思想是在代码库中表示这种“最佳方式”

首先,我们必须制定规则,定义一条特定记录是在另一条特定记录之前还是之后。字符串为“>=5 ha到<10 ha”的记录应该紧跟在值为“<5 ha”(在列表中的第二位)的记录之后。应该是这样的。或者,只需以已经排序的格式添加字符串,如果以后不需要重复使用,这是可以的。我不是100%你想说的(我读到:你会写一个类似的答案)。最后一句话一定要说;-)正如您所建议的那样,正确的方法是通过赋予字符串某种语义(例如,顺便说一句,通过可重用性,我的意思是您不能从