英文:
Sort ArrayList which consist of custom objects
问题
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 consists of respective getId() methods, etc.
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?
英文:
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?
答案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());
}
}
英文:
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())
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论