2017-07-25 78 views
1

我有我需要排序的字符串列表(请参见下文)。比较和排序具有数字和特殊字符的字符串

  • “<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()); 
     } 
    }  
    } 
+1

首先,我们必须提出规则来定义某个特定记录是在前一个还是后一个特定记录之后进行的。 –

+0

字符串“> = 5公顷到<10公顷”的记录应该在值等于“<5公顷”(位于列表中的第二位) –

回答

0

您可以使用流是这样的:

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

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

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

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

  • 创建表示一个类的(数学)间隔
  • 创建代码解析像“<5公顷”字符串转换成的间隔物
  • 然后排序间隔对象

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

重点是:您的字符串包含非常特别的信息。而良好的面向对象的整个想法是在你的代码库中表示这种“最好的方式”。

+0

击败我之后。那应该是这样。或者只是在已经排序好的格式中添加字符串,如果以后不需要重用它,那么也可以。 – nafas

+0

我不是100%你想说的(我读过:你会写出类似的答案)。坚持确定最后一句,虽然;-) – GhostCat

+0

正如你所建议的正确的做法,是通过给它一定的语义(例如<5小于<10等等)对字符串建模。这可能是一项非常困难的任务,但是如果你想要在网页中显示某些选项,那么通过牺牲可重用性来显示它们可能更容易。 – nafas