【问题标题】:Using Comparator in an object [closed]在对象中使用 Comparator [关闭]
【发布时间】:2014-10-10 09:45:15
【问题描述】:

我有一个名为Age 的类,它具有Yearsmonthsdays 属性。

我还有一个Age 实例列表。我想从该列表中找到最大年龄。为此,我想使用 Comparator 类。

任何帮助将不胜感激。

【问题讨论】:

  • 比较年份,如果相同则比较月份,如果相同则比较日期,就像您在现实生活中所做的那样。
  • 您需要向我们提供代码以及您尝试过的内容。
  • 您能告诉我们到目前为止您尝试过什么吗?
  • 将该字段提供为反射字段并对其应用比较器。您可能会在互联网上获得代码

标签: java collections comparator


【解决方案1】:

如果你想为每个字段创建自己的Comparator,请这样做

public static Comparator<Age> yearComparator = new Comparator<Age>() {
        @Override
        public int compare(Age age1, Age age2) {
            return age1.getYear() - age2.getYear();
        }
    };

然后

Arrays.sort(yourAgesArray, Age.yearComparator);

或者

Collections.sort(yourAgesArray, Age.yearComparator);

阅读此article 以更好地理解这一点。

【讨论】:

  • 为什么有单独的比较器?您可以很容易地在一个比较器中比较年、月和日。
  • 从 Java8 获得更好的:public static Comparator&lt;Age&gt; yearComparator = Comparator.comparing(Age::getYear);
【解决方案2】:

您可以编写一个如下所示的比较器:

Comparator<Age> ageComparator = new Comparator<Age>() {
    @Override
    public int compare(Age age1, Age age2) {
        if(age1.getYear() != age2.getYear()) {
            return age1.getYear() < age2.getYear() ? -1 : 1;
        } else if(age1.getMonth() != age2.getMonth()) {
            return age1.getMonth() < age2.getMonth() ? -1 : 1;
        } else if(age1.getDay() != age2.getDay()) {
            return age1.getDay() < age2.getDay() ? -1 : 1;
        } else {
            return 0;
        }
    }
}

【讨论】:

  • 投反对票的人愿意解释一下吗?
  • 谢谢它的工作:-)
  • @SukritKalia 很高兴听到它。 :) 然后您可以将此答案标记为已接受吗?
  • 我没有资格投票,因为我没有 15 票。我很乐意将您的回答标记为优秀。
  • @SukritKalia 您无需投票即可接受答案。在投票按钮下方有一个复选符号,您可以选择接受此答案为正确。
【解决方案3】:

您可能应该在 Age 类中实现 Comparable 接口。但是,您可能应该考虑使用第 3 方时间处理库或使用 java.time 中的一个(取决于您使用的 Java 版本)。比较时间有时会变得混乱。

当您的类实现Comparable 接口时,您可以使用平台中的Arrays.sort() 方法。

【讨论】:

    【解决方案4】:

    从 Java 8 开始,您可以使用这个单行解决方案:

    Age maxAge = collection
      .stream()
      .max(
         Comparator.comparing(Age::getYear)
        .thenComparing(Age::getMonth)
        .thenComparing(Age::getDay)
      )
      .get();
    

    【讨论】:

      猜你喜欢
      • 2020-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-19
      • 2019-10-18
      • 2014-04-28
      相关资源
      最近更新 更多