排序包含自定义对象的ArrayList。

huangapple go评论88阅读模式
英文:

Sort ArrayList which consist of custom objects

问题

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

  1. public History(long id, String res, double deposit, double odds, String sport, double ret, String user_name, Date date) {
  2. this.id = id;
  3. this.res = res;
  4. this.deposit = deposit;
  5. this.odds = odds;
  6. this.sport = sport;
  7. this.ret = ret;
  8. this.user_name = user_name;
  9. this.date = date;
  10. }

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:

  1. public History(long id, String res, double deposit, double odds, String sport, double ret, String user_name, Date date) {
  2. this.id = id;
  3. this.res = res;
  4. this.deposit = deposit;
  5. this.odds = odds;
  6. this.sport = sport;
  7. this.ret = ret;
  8. this.user_name = user_name;
  9. this.date = date;
  10. }

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

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

Alternatively, you can implement the comparable interface

  1. public class History implements Comparable<History> {
  2. // constructor, getters, and setters
  3. @Override
  4. public int compareTo(History h) {
  5. return Double.compare(getRet(), h.getRet());
  6. }
  7. }
英文:

Using java 8 streams Comparator

  1. List&lt;History&gt; sortedUsers = historyList.stream()
  2. .sorted(Comparator.comparing(History::getRet))
  3. .collect(Collectors.toList());

Alternatively you can implement the comparable interface

  1. public class History implements Comparable&lt;History&gt; {
  2. // constructor, getters and setters
  3. @Override
  4. public int compareTo(History h) {
  5. return Double.compare(getRet(), h.getRet())
  6. }
  7. }

huangapple
  • 本文由 发表于 2020年8月11日 16:36:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/63354516.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定