0

I have created a class called History. The constructor in this class looks like this:

public History(long id, String res, double deposit, double odds, String sport, double ret, String user_name, Date date) {
        this.id = id;
        this.res = res;
        this.deposit = deposit;
        this.odds = odds;
        this.sport = sport;
        this.ret = ret;
        this.user_name = user_name;
        this.date = date;   
    }

The class also consist of respective getId() methods ect.

The objects of the class "History" consist of different value types e.g. double, String and Date.

I then have an ArrayList of History objects which contains many of these objects. I want to sort the ArrayList by the highest values of "Double ret" e.g. Is there any way of doing this?

egx
  • 389
  • 2
  • 14
  • 2
    https://stackoverflow.com/questions/5245093/how-do-i-use-comparator-to-define-a-custom-sort-order – Kai Roper-Blackman Aug 11 '20 at 08:38
  • 3
    Implement the [Comparable Interface](https://docs.oracle.com/javase/8/docs/api/java/lang/Comparable.html) – Murat Karagöz Aug 11 '20 at 08:39
  • 1
    Or you could implement a [Comparator Interface](https://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html) – Amongalen Aug 11 '20 at 08:41
  • Perfect. Thank you all. This is exactly what I was looking for. Implementing the Comparator Interface solved my problem. However, I needed to convert double values for this to works. This is no problem in my case here, so it works for me. Thank you. – egx Aug 11 '20 at 08:45

1 Answers1

2

Using java 8 streams Comparator

List<History> sortedUsers = historyList.stream()
  .sorted(Comparator.comparing(History::getRet))
  .collect(Collectors.toList());

Alternatively you can implement the comparable interface

public class History implements Comparable<History> {
  
  // constructor, getters and setters
 
  @Override
  public int compareTo(History h) {
    return Double.compare(getRet(), h.getRet())
  }
}
Roie Beck
  • 1,113
  • 3
  • 15
  • 30
  • Thank you. As stated above, implementing the Comparator interface works for me. – egx Aug 11 '20 at 08:48
  • If I want to have more compareTo method, do you know how to do that? E.g. if I want to be able to sort by res, dep, odds – egx Aug 11 '20 at 09:04
  • 1
    The compare two method returns an int as result, you can do if(Double.compare(getRet(), h.getRet()) == 0) return Double.compare(getDep(), h.geDep()); and so on :), its a method you write the code inside it... – Roie Beck Aug 11 '20 at 09:10