【问题标题】:Sort an ArrayList based on an object field [duplicate]基于对象字段对ArrayList进行排序[重复]
【发布时间】:2011-05-03 06:22:32
【问题描述】:

可能重复:
Sorting an ArrayList of Contacts

我将DataNode 对象存储在ArrayList 中。 DataNode 类有一个名为 degree 的整数字段。 我想以degree 的递增顺序从nodeList 中检索DataNode 对象。我该怎么做。

List<DataNode> nodeList = new ArrayList<DataNode>();

【问题讨论】:

标签: java


【解决方案1】:

使用自定义比较器:

Collections.sort(nodeList, new Comparator<DataNode>(){
     public int compare(DataNode o1, DataNode o2){
         if(o1.degree == o2.degree)
             return 0;
         return o1.degree < o2.degree ? -1 : 1;
     }
});

【讨论】:

  • return(o1.degree - o2.degree); 怎么样?
  • 正确的方法是 Mark 编码的方式。是的,简单的一行代码将在 99.9% 的时间内工作。但是如果减法的结果是一个很大的数导致高位溢出,你就会遇到问题。例如,您希望 (Integer.MAX_VALUE - (-10)) 是正数,但事实并非如此。
  • @camickr o1.degree.compare(o2.degree) 怎么样?
  • Java 8 更新:Collection.sort(nodeList, Comparator.comparing(DataNode::getDegree)) 或 Collection.sort(nodeList, Comparator.comparingDouble(DataNode::getDegree)) 如果 degree 是 double而不是双
  • @Kazaag 您的评论应该是正确答案! :) Comparator.comparing... 方法也可以与Streams API 一起使用,如nodesList.stream().sorted(Comparator.comparing(DataNode::getDegree)).collect(Collector.toList())
【解决方案2】:

修改 DataNode 类,使其实现 Comparable 接口。

public int compareTo(DataNode o)
{
     return(degree - o.degree);
}

然后就用

Collections.sort(nodeList);

【讨论】:

  • Beware of overflow!return Integer.compare(this.degree, o.degree); 更安全
  • 由于某种原因,如果我不输入对象会出错
  • 这将失败,因为没有对 null 的检查。你也不需要括号
  • 我遇到了一个问题,我必须使用 Object 作为方法调用中的类型,并且我无法将其转换为我的对象类型(本例中为 DataNode)
  • 你的类必须实现 Comparable 而不仅仅是实现 Comparable。
【解决方案3】:

您可以使用Bean Comparator 对自定义类中的任何属性进行排序。

【讨论】:

    猜你喜欢
    • 2017-09-17
    • 1970-01-01
    • 1970-01-01
    • 2014-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-21
    • 1970-01-01
    相关资源
    最近更新 更多