我有一个列表
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);
我按价格排序并反转结果
formattedResult = list.stream().sorted(Comparator.comparing(m -> Double.parseDouble(m.get("price")))).collect(Collectors.toList());
Collections.reverse(formattedResult);
结果:
**price productNumber**
1.99 109-001
1.99 107-001
1.02 108-001
我想像这样排序
**price productNumber**
1.99 107-001
1.99 109-001
1.02 108-001
如果价格相等 - 按产品编号进行比较,最后应该是具有较低值的产品编号。 请帮忙!
最佳答案
如果您使用正确的比较器,则不需要反转结果(并且您也可以链接比较器):
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());
关于java - 如果 key1 具有相同的值,如何按 key1 降序和 key2 升序对 List<Map<String,String>> 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60730863/