简体   繁体   中英

Sort List of Values in a Map in descending order

I have a Map with List of Doubles.

unsorted map contents: {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]}

I need to sort in descending order for List(0). I have tried the below logic but its sorting in ascending order.

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

Actual 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]}

Expected 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]}

Please help me with logic on Java8 streams.

Try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM