基于对象字段对ArrayList进行排序

dev*_*ull 76 java

可能重复:
对联系人的ArrayList进行排序

我正在存储DataNode对象ArrayList.该DataNode班有一个名为整型字段degree.我想以DataNode递增的顺序从nodeList 检索对象degree.我该怎么做.

List<DataNode> nodeList = new ArrayList<DataNode>();
Run Code Online (Sandbox Code Playgroud)

Mar*_*iot 170

使用自定义比较器:

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;
     }
});
Run Code Online (Sandbox Code Playgroud)

  • 这样做的正确方法是Mark对其进行编码的方式.是的,简单的一行代码将在99.9%的时间内起作用.但是如果减法的结果是一个很大的数字导致高阶位溢出,那么你会遇到问题.例如,你期望(Integer.MAX_VALUE - ( - 10))是积极的,但事实并非如此. (22认同)
  • Java 8更新:Collection.sort(nodeList,Comparator.comparing(DataNode :: getDegree))或Collection.sort(nodeList,Comparator.comparingDouble(DataNode :: getDegree))如果degree是double而不是Double (7认同)
  • 如何回归(o1.degree - o2.degree);? (6认同)
  • @Kazaag你的评论应该是正确答案!:)`Comparator.comparing ...`方法也可以和`streams`s API一起使用,如`nodesList.stream().sorted(Comparator.comparing(DataNode :: getDegree)).collect(Collector.toList) ())` (4认同)

bli*_*egz 61

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

public int compareTo(DataNode o)
{
     return(degree - o.degree);
}
Run Code Online (Sandbox Code Playgroud)

然后只是使用

Collections.sort(nodeList);
Run Code Online (Sandbox Code Playgroud)

  • [小心溢出!](/sf/ask/191015541/)返回Integer.compare(this.degree,o.degree)更安全; (3认同)