1

How to sort a list using comparator in Descending order (based on salary which is a long value)


class Empl{

    private String name;
    private long salary;

    public Empl(String n, long s){
        this.name = n;
        this.salary = s;
    }

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public long getSalary() {
        return salary;
    }
    public void setSalary(long salary) {
        this.salary = salary;
    }

}
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
Devrath
  • 42,072
  • 54
  • 195
  • 297

4 Answers4

4

If you are using Java 8 you can use Stream#sorted with Comparator#comparingLong like this :

list = list.stream()
        .sorted(Comparator.comparingLong(Empl::getSalary).reversed())
        .collect(toList());

Note the .reversed() when you use it the list is sorted descendant, else if you don't use it, it is sorted ascendant.

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
  • Minor, but you’ve got your ascending and descending words mixed up. It should be the reciprocal of what you’ve mentioned. Also it’s better to use Comparator.conparingLong to avoid the overhead of boxing and unboxing. – Ousmane D. Mar 15 '18 at 08:41
1

Try this:

Descending

Collections.sort(modelList, new Comparator<Empl>() {
        @Override
        public int compare(Empl o1, Empl o2) {
            return o2.getSalary().compareTo(o1.getSalary());
        }
});

Ascending

Collections.sort(modelList, new Comparator<Empl>() {
            @Override
            public int compare(Empl o1, Empl o2) {
                return o1.getSalary().compareTo(o2.getSalary());
            }
});
Bourbia Brahim
  • 14,459
  • 4
  • 39
  • 52
Tung Tran
  • 2,885
  • 2
  • 17
  • 24
0

Use this way

Collections.sort(employeeList, new Comparator<VariationsItem>() {
    @Override
    public int compare(Empl lhs, Empl rhs) {
        return ((Long) rhs.getSalary()).compareTo((Long) lhs.getSalary());
    }
});
slavoo
  • 5,798
  • 64
  • 37
  • 39
Ramkumar.M
  • 681
  • 6
  • 21
0

If you’re using Java-8 then you can call the default sort method directly on the list providing the necessary comparator.

list.sort(Comparator.comparingLong(Empl::getSalary).reversed());
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126