0

obj contains name price date

How do I order by date, name or price with ascending and descendeding functionalities?

thank you for your time

2
  • what if it's an ArrayList Commented Jun 17, 2020 at 11:03
  • An ArrayList is a type of List, so that's fine. Commented Jun 18, 2020 at 3:40

1 Answer 1

2

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;
  }
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.