简体   繁体   中英

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

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM