Search code examples
javasortingdictionarycollectionscomparator

How to sort Map entries by values first, then by key and put the ordered keys in a List?


I have an HashMap :

private Map<String,Integer> matchesWonByTeam= new HashMap<String,Integer>();
  • I need to order those teams by matches won (value) and return an ArrayList with the names of the teams.
  • If any of those teams have the same amount of matches won they need to be alphabetically ordered.

What is the shortest and simplest way to do that using Collections and Comparators?


Solution

  • You could do it that way using functional programming :

    final Map<String, Integer> map = new HashMap<>();
    map.put("test", 1);
    map.put("test1", 3);
    map.put("test3", 4);
    map.put("test2", 75);
    map.put("a", 75);
    map.put("test100", 100);
    
    final List<String> test = map
            .entrySet()
            .stream()
            .sorted((Entry<String, Integer> o1, Entry<String, Integer> o2) -> {
                  return o1.getValue().equals(o2.getValue()) ? 
                              o1.getKey().compareTo(o2.getKey()) 
                                  : o1.getValue().compareTo(o2.getValue());
              })
            .map(e -> e.getKey())
            .collect(Collectors.toList());
    
    for(String s : test)
          System.out.println(s); 
    

    This example would output

    test test1 test3 a test2 test100