微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在一个比较器上使用多个条件对对象的 Arraylist 进行排序?

如何解决如何在一个比较器上使用多个条件对对象的 Arraylist 进行排序?

我正在尝试使用 Kotlin 集合 (SortedSet) 在 Java 中实现一个比较器。在我的数组列表中,我有多个 Arraylist<Payment>() 对象。我还有一个付款哈希图,其中包含一些付款 HashMap<String,Integer>() in getPaymentIds(),字符串值是我的付款 ID,整数是计数

我的排序顺序是首先将Hashmap中包含的值大于1的所有付款按整数值(计数)排序,然后是不在Hashmap中的付款

这是我一直在玩的,但问题是它返回一个只有一个元素的 Set

public final int compare(final Payment o1,final Payment o2) {
        boolean b2 = true;
        if (getPaymentIds().get(o2.getId()) != null) {
            final Integer count = getPaymentIds().get(o2.getId());
            
            if (Intrinsics.compare(count,1) >= 0) {
                b2 = false;
            }
        }

        boolean b = false;
        if (getPaymentIds.get(o1.getId()) != null) {
            final Integer value3 = getPaymentIds.get(o1.getId());
            
            if (Intrinsics.compare(value3,1) < 0) {
                b = true;
            }
        }

        return ComparisonsKt.compareValues(b2,b);

我已经玩过这段代码,最接近的是接收只有一个元素的排序集

解决方法

您可以叠加支票。在我的示例中,我使用 a、b 和 c 作为 Payment

中的值字段
public int compareTo(Payment p1,Payment p2) {
  int diff = p2.a == null ? -1 : p2.a - p1.a == null ? -1 : p1.a; // if a is a number,than p2.a - p1.a correctly returns the order (as per compareTo's api) between them
  if (diff != 0) return diff;
  diff = p2.b == null ? -1 : p2.b - p1.b == null ? -1 : p1.b;
  if (diff != 0) return diff;
  diff = p2.c == null ? -1 : p2.c - p1.c == null ? -1 : p1.c;
  return diff; // if diff is still 0,the objects are equal,and either order is acceptable    
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。