[英]How to sort List<Map<String,String>> by key1 descending order and key2 ascending order if key1 has same values
[英]Sort List of Values in a Map in descending order
我有一個帶有雙打列表的 Map。
未排序的 map 內容:{A=[0.02, 0.03], B=[0.0, 0.01], C=[0.01, 0.0], D=[0.05, 1.03], E=[1.01, 0.03]}
我需要對 List(0) 進行降序排序。 我嘗試了以下邏輯,但它按升序排序。
Map<String, List<Double>> map = new HashMap<>();
map.put("A", new ArrayList<Double>(Arrays.asList(0.02,0.03)));
map.put("B", new ArrayList<Double>(Arrays.asList(0.00,0.01)));
map.put("C", new ArrayList<Double>(Arrays.asList(0.01,0.00)));
map.put("D", new ArrayList<Double>(Arrays.asList(0.05,1.03)));
map.put("E", new ArrayList<Double>(Arrays.asList(1.01,0.03)));
Map<String, List<Double>> output = map.entrySet()
.stream()
.sorted(Comparator.comparing(o -> o.getValue().get(0)))
.collect(Collectors
.toMap(Map.Entry::getKey,Map.Entry::getValue,(a,b) ->a, LinkedHashMap :: new));
System.out.println("After sort: " + output);
實際 output: {B=[0.0, 0.01], C=[0.01, 0.0], A=[0.02, 0.03], D=[0.05, 1.03], E=[1.01, 0.03]}
預期 output:{E=[1.01, 0.03], D=[0.05, 1.03], A=[0.02, 0.03], C=[0.01, 0.0], B=[0.0, 0.1]}
請幫助我了解 Java8 流的邏輯。
嘗試這個:
Map<String, List<Double>> output = map.entrySet()
.stream()
.sorted(Collections.reverseOrder(Comparator.comparing(o -> o.getValue().get(0))))
.collect(Collectors
.toMap(Map.Entry::getKey,Map.Entry::getValue,(a,b) ->a, LinkedHashMap :: new));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.