簡體   English   中英

如何排序列表<Map<String,String> &gt; 如果 key1 具有相同的值,則按 key1 降序和 key2 升序

[英]How to sort List<Map<String,String>> by key1 descending order and key2 ascending order if key1 has same values

我有一個清單

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

如果價格相等 - 按產品編號比較,最先結束的應該是具有較低值的 productNumber。 請幫忙!

如果您使用正確的比較器(並且您也可以鏈接比較器),則不需要反轉結果:

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

如果您分兩步構建Comparator更容易。 所以試試這個並將它們打印出來。 它是這樣工作的。

  • 首先它以相反的順序對價格進行排序。
  • 然后 t 將產品編號按相同的價格按常規順序排序。
    Comparator<Map<String, String>> comp = Comparator
        .comparing(m ->Double.parseDouble(m.get("price"))
                         ,Comparator.reverseOrder());
    comp = comp.thenComparing(m -> m.get("productNumber"));

像這樣應用它。

        List<Map<String, String>> formattedResult =
                list.stream().sorted(comp)  
                        .collect(Collectors.toList());


        formattedResult.forEach(m -> System.out.println(
                m.get("price") + " : " + m.get("productNumber")));

這打印

1.99 : 107-001
1.99 : 109-001
1.02 : 108-001


您可以為productNumber創建反向比較器

 Comparator<Map<String, String>> productNumberReversed =  Comparator.comparing((Map<String, String> mp) -> mp.get("productNumber")).reversed();

然后使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM