obj contains name price date
How do I order by date, name or price with ascending and descendeding functionalities?
thank you for your time
obj contains name price date
How do I order by date, name or price with ascending and descendeding functionalities?
thank you for your time
There are some method to do that.
1, Streams:
list.stream()
.sorted(Comparator.comparing(MyObject::getPrice))
.collect(Collectors.toList())
For the reversing order:
list.stream()
.sorted(Comparator.comparing(MyObject::getName).reversed())
.collect(Collectors.toList())
2, Comparator
list.sort(comparator) or Collections.sort(list,comparator)
Comparator<MyObj> priceComparator=new Comparator<MyObj>() {
@Override
public int compare(MyObj o1, MyObj o2) {
//Note that compareTo only available if you implement comparable
//If not, return values I describe later
//Or use Comparator.comparing(field/keyExtractor)
return o1.getPrice().compareTo(o2.getPrice());
}
})
You can create implementation to any field. You can implement logic here to combine fields etc.
3, Implement Comparable interface in the Data object.
public class MyObj implements Comparable<MyObj> {
@Override
public int compareTo(MyObj o) {
return price.compareTo(o.getPrice());
}
[...]
}
Comparator is much more flexible then Comparable, because you can select the behaviour runetime.
If you need custom logic, you can write it in the compare method.
You can return with:
0 if equals
1 if left is greater
-1 if right is greater
For example in a custom Comparator:
public int compare(MyObj o1, MyObj o2) {
int result=0;
if(o1.price>o2.price) result=1;
[...]
return result;
}