Search code examples
sortingcollectionsjava-8java-stream

A map where the value is a list of lists - how to sort the list?


I have a Map where the Key is a String and the Value is a List of 'Plan' objects. For each key, I want the value (i.e. the list of Plan objects) to be sorted on the Plan's fee field.

For example, IF: Plan1 has a fee of 100.20, Plan 2 has a fee of 400.10, Plan 3 has a fee of 10.00 AND: Before sorting the entry is: ["abc", [Plan1 , Plan2, Plan3]] THEN: After sorting the entry should be: ["abc", [Plan3 , Plan1, Plan2]]

I have tried

map.values()
.forEach(lst -> lst.stream()
.sorted(Comparator.comparingDouble(Plan::getFee)))
.collect(Collectors.toList())
);

but this did not change the order of the lists.

Is there a way to do this using Streams?


Solution

  • Hey here is the solution to your problem, I have also tested on my machine.

    If you have a getter method getFee() for the fee variable in your Plan Class. Then the below one works well for you.

    hmap.entrySet().forEach(e->e.getValue().sort(Comparator.comparing(Plan::getFee)));
    

    Thanks to @tgdavies for much simpler approach. Here is the code for same.

    hmap.values().forEach(li->li.sort(Comparator.comparing(Plan::getFee)));