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.
JavaScript
x
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.
Advertisement
Answer
Try this:
JavaScript
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));