Java - Collections.sort在List <myobject> </myobject>上对我不起作用

时间:2015-02-20 07:56:31

标签: java list collections

我有一个包含人物姓氏的对象列表。我想按升序对此列表进行排序,但排序方法在我的列表中不起作用。 这是代码:

  Collections.sort(resultList, new Comparator<KeyValue>()
  {
     public int compare(final KeyValue keyValue1, final KeyValue keyValue2)
     {
        return keyValue1.getLastName().compareTo(keyValue2.getLastName());
     }

  });

2 个答案:

答案 0 :(得分:1)

由于您没有提供MVC example,我必须猜测您的对象是什么,但它对我有用:

public static void main(String[] args) {
    List<KeyValue> resultList = new ArrayList<KeyValue>();
    resultList.add(new KeyValue("Mauer"));
    resultList.add(new KeyValue("Bauer"));
    resultList.add(new KeyValue("Friedrich"));

    System.out.println("Before: " + Arrays.toString(resultList.toArray(new KeyValue[0])));

    Collections.sort(resultList, new Comparator<KeyValue>() {
        public int compare(final KeyValue keyValue1, final KeyValue keyValue2) {
            return keyValue1.getLastName().compareTo(keyValue2.getLastName());
        }
    });

    System.out.println("After: " + Arrays.toString(resultList.toArray(new KeyValue[0])));
}

static class KeyValue {
    private String lastName;

    public KeyValue(String lastName) {
        this.lastName = lastName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    @Override
    public String toString() {
        return lastName;
    }
}

输出:

  

之前:[Mauer,Bauer,Friedrich]
  之后:[鲍尔,弗里德里希,毛尔]

答案 1 :(得分:0)

感谢您的帮助。我现在解决了。

排序不起作用,因为添加到列表中的最后一个值是小写的。它适用于compareToIgnoreCase()方法。

Collections.sort(resultList, new Comparator<KeyValue>()
{
 public int compare(final KeyValue keyValue1, final KeyValue keyValue2)
 {
    return keyValue1.getLastName().compareToIgnoreCase(keyValue2.getLastName());
 }

});