Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a list of objects with some specific property

Tags:

java

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 less value of simiADD should occur first and record with more value of simiADD should occur later in the sorted list. I wanted to do this operation in a seprate method and not implementing the comparator in Record class.

like image 228
Saurabh Kumar Avatar asked Dec 13 '25 00:12

Saurabh Kumar


2 Answers

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);
        }
    }
);
like image 178
Ted Hopp Avatar answered Dec 14 '25 14:12

Ted Hopp


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);
    }
}
like image 39
Erhan Bagdemir Avatar answered Dec 14 '25 13:12

Erhan Bagdemir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!