Search code examples
javasortinghashmaptreemap

Sorting a HashMap or TreeMap by value


I am making a java project which records football games and displays the league table. When a game is added to the league between two teams, I need a way of storing the teams position in the league based on the number of points that the Team have.

To do this is am thinking of using a HashMap< Integer, Team > where the Integer is storing the Teams position in the league based on the number of points that a team has. Whenever a new game is added I need a way of ordering this list so that it is sorted where the Teams with the greatest number of points are closer to the number one position.

For example, if there are three teams

Team A with 8 points, Team B with 5 points, Team C with 4 point

I would like the Map to be ordered as such

1 : A, 2 : B, 3 : C

My question are:

1) Do you think I should be using a HashMap or TreeMap for this instance?

2) How would I implement the code to sort the league by points aquired?


Solution

  • A List is more appropriate for your use case. It gives you indexing out of the box and hassle-free sorting. Additionally, it's more suited for ordered display of values such as in a table, etc.

    I would make the Team object comparable, use an array list, then I'd be done:

    public class Team implements Comparable<Team> {
        private int points;
        private int goalDifference;
    
        public Team(int points, int goalDifference) {
            this.points = points;
            this.goalDifference = goalDifference;
        }
    
        @Override
        public int compareTo(Team other) {
            int res = other.points - this.points;
            return res != 0 ? res : (other.goalDifference - this.goalDifference);
        }
    
        //getters and setters
    }
    

    With a comparable Team class, you can use list features:

    List<Team> teams = ...
    Collections.sort(teams);
    

    If you don't want to make the Team class comparable, you can use a comparator (continuing the snippet above):

    teams.sort((team1, team2) -> 
       (team2.getPoints() != team1.getPoints()) ? 
         (team2.getPoints() - team1.getPoints()) : 
         (team2.getGoalDifference() - team1.getGoalDifference())
       );
    

    Note that implemented the descending order logic in comparables or comparators. You can choose to use the reverse comparator instead.

    The option of implementing Comparator becomes more and more preferable as the number of comparison fields grows. I'd personally prefer that as it's more readable.