Java 基于对象字段对ArrayList排序
可能重复:Java 基于对象字段对ArrayList排序,java,Java,可能重复: 我正在将DataNode对象存储在ArrayList中。DataNode类有一个名为degree的整数字段。 我想从nodeList中以度的递增顺序检索DataNode对象。我该怎么做呢 List<DataNode> nodeList = new ArrayList<DataNode>(); List nodeList=new ArrayList(); 使用自定义比较器: Collections.sort(nodeList, new Comparator&
我正在将
DataNode
对象存储在ArrayList
中。DataNode
类有一个名为degree
的整数字段。
我想从nodeList中以度
的递增顺序检索DataNode
对象。我该怎么做呢
List<DataNode> nodeList = new ArrayList<DataNode>();
List nodeList=new ArrayList();
使用自定义比较器:
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;
}
});
Collections.sort(nodeList,newcomparator(){
公共整数比较(数据节点o1、数据节点o2){
如果(o1.degree==o2.degree)
返回0;
返回o1.degree
您可以使用对自定义类中的任何属性进行排序。修改DataNode类,使其实现可比较的接口
public int compareTo(DataNode o)
{
return(degree - o.degree);
}
那就用
Collections.sort(nodeList);
第二个图上可能出现的重复可能更接近于此,请参见返回(o1.degree-o2.degree);?正确的方法是马克对其进行编码。是的,简单的一行代码将在99.9%的时间内工作。但是,如果减法的结果是一个大数字,导致高阶位溢出,则会出现问题。例如,您可能希望(Integer.MAX_VALUE-(-10))为正,但事实并非如此。@camickr o1.degree.compare(o2.degree)如何?Java 8更新:Collection.sort(nodeList,Comparator.comparating(DataNode::getDegree))或Collection.sort(nodeList,Comparator.comparingDouble(DataNode::getDegree))如果学位是双学位而不是双学位Double@Kazaag您的评论应该是正确的答案!:)
Comparator.comparing…
方法也可以与Stream
s API一起使用,如nodesList.Stream().sorted(Comparator.comparing(DataNode::getDegree)).collect(Collector.toList())
比返回整数更安全代码>由于某种原因,如果我不输入对象,我会得到一个错误。这将失败,因为没有检查null。另外,您不需要括号。我遇到一个问题,我必须在方法调用中使用Object
作为类型,并且我不能将其转换为我的对象类型(本例中为DataNode)。您的类必须实现Comparable,而不仅仅是实现Comparable。