【问题标题】:Sort ArrayList which consist of custom objects [duplicate]排序由自定义对象组成的ArrayList [重复]
【发布时间】:2020-08-11 08:36:57
【问题描述】:

我创建了一个名为 History 的类。此类中的构造函数如下所示:

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;   
    }

该类还包含各自的 getId() 方法等。

“历史”类的对象由不同的值类型组成,例如双精度、字符串和日期。

然后我有一个包含许多这些对象的历史对象的 ArrayList。我想按“Double ret”的最高值对 ArrayList 进行排序,例如有没有办法做到这一点?

【问题讨论】:

标签: java sorting arraylist


【解决方案1】:

使用 java 8 流比较器

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

您也可以实现类似的接口

public class History implements Comparable<History> {
  
  // constructor, getters and setters
 
  @Override
  public int compareTo(History h) {
    return Double.compare(getRet(), h.getRet())
  }
}

【讨论】:

  • 谢谢。如上所述,实现 Comparator 接口对我有用。
  • 如果我想要更多的 compareTo 方法,你知道怎么做吗?例如。如果我希望能够按 res、dep、赔率排序
  • 比较两个方法返回一个int作为结果,你可以这样做 if(Double.compare(getRet(), h.getRet()) == 0) return Double.compare(getDep(), h.geDep());等等:),它是一种你在里面写代码的方法......
猜你喜欢
  • 2018-12-15
  • 1970-01-01
  • 2020-07-07
  • 2016-06-17
  • 1970-01-01
  • 2015-07-10
  • 1970-01-01
  • 2010-12-21
相关资源
最近更新 更多