How to sort a list of objects with some specific property

前端 未结 4 1534
-上瘾入骨i
-上瘾入骨i 2021-01-20 13:38

I have a record object

 public Record{
   double simiADD;
 }

I Have a List of Record objects and I want to Sort on simiADD. Record with le

相关标签:
4条回答
  • 2021-01-20 13:42

    If you don't want to define a comparison function inside the Record class:

    Collections.sort(recordList, new Comparator<Record>() {
            public int compare(Record object1, Record object2) {
                return Double.compare(object1.simiADD, object2.simiADD);
            }
        }
    );
    
    0 讨论(0)
  • 2021-01-20 13:44

    I assume that you meant that you don't want to implement "Comparable" interface in your class. Use Comparator and Collection's sort static method:

    import java.util.*;
    public class EmpSort {
        static final Comparator<Employee> SENIORITY_ORDER =
                                     new Comparator<Employee>() {
            public int compare(Employee e1, Employee e2) {
                return e2.hireDate().compareTo(e1.hireDate());
            }
        };
    
        // Employee database
        static final Collection<Employee> employees = ... ;
    
        public static void main(String[] args) {
            List<Employee>e = new ArrayList<Employee>(employees);
            Collections.sort(e, SENIORITY_ORDER);
            System.out.println(e);
        }
    }
    
    0 讨论(0)
  • 2021-01-20 13:50

    Read the JavaDoc for the Comparable interface. http://download.oracle.com/javase/6/docs/api/java/lang/Comparable.html. Or did you mean "don't want to implement Comparable" instead of "Comparator"?

    Comparable is quite standard actually, which is good for the maintenance of your code. The sort method in Collections is based on it, so it works pretty well.

    0 讨论(0)
  • 2021-01-20 14:02

    Here's a code example

    public class Record implements Comparable<Record> {
        public double simiADD;
    
        public int compareTo(Record r) {
            return Double.compare(this.simiADD, r.simiADD);
        }
    }
    

    Then simply using any sort method will use the overridden compareTo for the Record class.

    0 讨论(0)
提交回复
热议问题