比较器首先对匹配的字符串进行排序,然后使用默认的排序顺序进行排序 [英] Comparator sort matching String at first, and rest using default sorting order

查看:60
本文介绍了比较器首先对匹配的字符串进行排序,然后使用默认的排序顺序进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

String currency = EUR;

List<Payment> payments = #has payments, with one field being Currency;

//This is not it:
payments.sort(Comparator.comparing(o -> o.getCurrency().equals(currency));

在我的情况下,我希望所有货币等于变量 currency 的付款都位于列表的顶部,其他订单保持不变.

I want all the payments which currency equals to variable currency in my case EUR to be at the top of the list, others order stays the same.

如果没有什么与变量 currency 相等,则按默认值排序,例如USD.

And if there is nothing that equals with the variable currency then sort by default value which for example is USD.

我知道这可以通过其他方法来完成,但这是一种挑战,有人可以帮我解决我从第一部分开始所缺少的东西吗?

I know this can be done other ways, but this is kind of a challenge, can someone help, what I am missing from the first part, to order by equals.

推荐答案

您需要具有自定义比较器逻辑,以便首先使用 currency = EUR 对对象进行排序,然后使用自然排序顺序对其余对象进行排序

You need to have custom comparator logic to sort the object with currency = EUR at first and rest of them using natural sorting order

List<Payment> list = new ArrayList<>(List.of(new Payment("EUR"),new Payment("EUR"),new Payment("AUS"),new Payment("INR"),new Payment("INR")));



    list.sort((c1,c2)->{

        if (c1.getCurrency().equals("EUR")) {
            return c2.getCurrency().equals("EUR") ? 0 : -1;
        }
        if (c2.getCurrency().equals("EUR")) {
            return 1;
        }
        return c1.getCurrency().compareTo(c2.getCurrency());

    });

    System.out.println(list);  //[Payment [currency=EUR], Payment [currency=EUR], Payment [currency=AUS], Payment [currency=INR], Payment [currency=INR]]

这篇关于比较器首先对匹配的字符串进行排序,然后使用默认的排序顺序进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆