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

时间:2017-07-25 11:21:09

标签: java

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

  • "< 5公顷"
  • "> = 10公顷至< 20公顷"
  • "> = 20公顷至< 50公顷"
  • "> = 5公顷至< 10公顷"
  • "> = 50 Ha"

看起来很简单,但直到现在,我还没有找到一个简单的方法。 Element类只有一个名为code的String类型的属性。 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());
        }   
    }    
  }

2 个答案:

答案 0 :(得分:2)

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

你不应该把你的问题视为“字符串”排序。您会看到,这些字符串代表区间(或范围)信息。

含义:虽然它可能看起来像“更多工作”,但您应该考虑建模这些方面。换句话说:

  • 创建一个代表(数学)区间的类
  • 创建将“&lt; 5 ha”之类的字符串解析为间隔对象的代码
  • 然后对间隔对象进行排序

不如创建自己的类,您也可以查看第3方库,如here所述。

重点是:您的字符串包含非常特殊的信息。好的OOP的整个想法是在代码库中表示这种“最好的方法”。

答案 1 :(得分:0)

你可以使用这样的流:

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