Search code examples
javalistdictionaryjava-stream

How to use group By for a map in java?


I have list which contains a map List<Map<String, Object>> map has two keys which is a id and the amount. I want to sort the list descending order base on the amount key, if the amount is same for two elements in the list then sort it based on the id. How can I do this ?


    List<Map<String, Object>> list = new ArrayList<>();
    Map<String, Object> hm = new HashMap<>();
    hm.put(id, 1);
    hm.put(amount, 25000);
    list.add(hm);

index of list element = 1, 2, 3 ,4 ,5 ,6

values for id = 1, 2, 3 ,4 ,5, 4

values for amount = 10000, 450000, 25000, 45000, 35000, 75000

list should sorted as follows(index of list) = 6, 4 (id is large), 2, 5, 3, 1


Solution

  • There are a lot of possibilities, this one modifies the original list:

    Comparator<Map<String, Object>> sortByAmount = Comparator.comparing(m -> (int) m.get("amount"));
    Comparator<Map<String, Object>> sortById = Comparator.comparing(m -> (int) m.get("id"));
    
    list.sort(sortByAmount.reversed().thenComparing(sortById));
    

    If you want to preserve the original list, you can use the stream api:

    list.stream().sorted(sortByAmount.reversed().thenComparing(sortById));