[英]How to sort List<Map<String,String>> by key1 descending order and key2 ascending order if key1 has same values
I have a List我有一个清单
List<Map<String,String>> list = new ArrayList<>();
Map<String,String> map = new HashMap<>();
Map<String,String> map1 = new HashMap<>();
Map<String,String> map2 = new HashMap<>();
map.put("productNumber", "107-001");
map1.put("productNumber", "108-001");
map2.put("productNumber", "109-001");
map.put("price", "1.99");
map1.put("price", "1.02");
map2.put("price", "1.99");
list.add(map);
list.add(map1);
list.add(map2);
I sort it by price and revers result我按价格排序并反转结果
formattedResult = list.stream().sorted(Comparator.comparing(m -> Double.parseDouble(m.get("price")))).collect(Collectors.toList());
Collections.reverse(formattedResult);
The result of this :这样做的结果:
**price productNumber**
1.99 109-001
1.99 107-001
1.02 108-001
I want to sort it like我想把它排序
**price productNumber**
1.99 107-001
1.99 109-001
1.02 108-001
If prices equal - compare by product number, end first should be productNumber with a lower value.如果价格相等 - 按产品编号比较,最先结束的应该是具有较低值的 productNumber。 Please help!
请帮忙!
You don't need to reverse result if you use the right comparator (and you can chain comparators, too):如果您使用正确的比较器(并且您也可以链接比较器),则不需要反转结果:
final Comparator<Map<String, String>> byPrice = Comparator.comparing(m -> Double.parseDouble(m.get("price")), Comparator.reverseOrder());
formattedResult = list.stream().sorted(byPrice.thenComparing(m -> m.get("productNumber"))).collect(Collectors.toList());
It's easier if you build your Comparator
in two steps.如果您分两步构建
Comparator
更容易。 So try this and print them out.所以试试这个并将它们打印出来。 It works like this.
它是这样工作的。
Comparator<Map<String, String>> comp = Comparator
.comparing(m ->Double.parseDouble(m.get("price"))
,Comparator.reverseOrder());
comp = comp.thenComparing(m -> m.get("productNumber"));
Apply it like so.像这样应用它。
List<Map<String, String>> formattedResult =
list.stream().sorted(comp)
.collect(Collectors.toList());
formattedResult.forEach(m -> System.out.println(
m.get("price") + " : " + m.get("productNumber")));
This prints这打印
1.99 : 107-001
1.99 : 109-001
1.02 : 108-001
You can create reverse comparator for productNumber
您可以为
productNumber
创建反向比较器
Comparator<Map<String, String>> productNumberReversed = Comparator.comparing((Map<String, String> mp) -> mp.get("productNumber")).reversed();
And then add it sort method comparator using thenComparing然后使用thenComparing添加排序方法比较器
formattedResult = list.stream()
.sorted(Comparator.comparing((Map<String, String> m) -> Double.parseDouble(m.get("price"))).thenComparing(productNumberReversed)).collect(Collectors.toList());
Collections.reverse(formattedResult);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.