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;
}
}
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.
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());
}
});
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());
}
});
如果您使用的是Java-8,则可以直接在列表上调用默认的sort方法,以提供必要的比较器。
list.sort(Comparator.comparingLong(Empl::getSalary).reversed());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.