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?

4
  • 2
    stackoverflow.com/questions/5245093/… Commented Aug 11, 2020 at 8:38
  • 3
    Implement the Comparable Interface Commented Aug 11, 2020 at 8:39
  • 1
    Or you could implement a Comparator Interface Commented Aug 11, 2020 at 8: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. Commented Aug 11, 2020 at 8:45

1 Answer 1

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

3 Comments

Thank you. As stated above, implementing the Comparator interface works for me.
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
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...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.