Comparator sort matching String at first, and rest using default sorting order

非 Y 不嫁゛ 提交于 2021-02-04 21:06:56

问题


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

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.

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.


回答1:


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]]



回答2:


If you are just looking to get the sort function to work for you, then your Comparator can return a negative value for your EUR currency giving it the lowest position in your sort order and treat all others as equal. If you want to maintain order within your EUR currency objects, you will have to expand on this further.

list.sort((o1, o2) -> o1.currency.equals("EUR") ? -1 : 0);


来源:https://stackoverflow.com/questions/61126325/comparator-sort-matching-string-at-first-and-rest-using-default-sorting-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!