英文:
Comparator sort matching String at first, and rest using default sorting order
问题
String currency = EUR;
List<Payment> payments = #具有支付信息,其中一个字段是货币;
// 这不是所需的:
payments.sort(Comparator.comparing(o -> o.getCurrency().equals(currency));
我希望所有货币与变量**currency**(在我的情况下为EUR)相等的支付位于列表的顶部,其他支付顺序保持不变。
如果没有与变量**currency**相等的支付,则按默认值排序,例如USD。
我知道还有其他方法可以实现,但这是一种挑战,有人能帮忙吗?从第一部分缺少什么,可以按相等条件排序。
英文:
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
得分: 1
你需要有自定义的比较器逻辑,以便将币种为 EUR
的对象排在前面,其余对象按自然排序顺序排列。
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]]
英文:
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
得分: -1
如果您只是希望使排序功能正常工作,那么您的比较器可以为您的欧元货币返回一个负值,使其在排序顺序中处于最低位置,并将其他所有货币视为相等。如果您希望在欧元货币对象内保持顺序,您将需要进一步扩展此功能。
list.sort((o1, o2) -> o1.currency.equals("EUR") ? -1 : 0);
英文:
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);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论