Turning a Map into a SortedMap with different keys

57 Views Asked by At

im having a hard time understanding Maps and i was asked to make a SortedMap with a different key and value out of another map using a comparator and a supplier. Its said to us that the "teams" key is the name of a team and the value is the information of the team, and the new sorted map has as a key the points that a team has and as a value the colection of team names with that points, the colection is given by the supplier. i dont get how i will make that happen. i thought of verifing if in "teams" there is a key with on of the suppliers name by iterating this one and if there was i would save that name in an List. but after that i dont know how i would build the SortedMap. Any suggestions?

Edited: This was what i did.

public static <C extends Collection<String>> SortedMap<Integer, C> toTable(Map<String, Team> teams, Comparator<Integer> cmp, Supplier<C> supplier) {
  SortedMap<Integer, C> sm = new TreeMap<Integer, C>(cmp);
  List<C> aux= new ArrayList<C>();
  C newTeam = null;
  int totalNames = supplier.get().size();
  while(totalNames>0) {
    if(teams.containsKey(supplier.get().iterator().next()))
        aux.add(supplier.get());
        totalNames--;
  }

  int size = aux.size();
  while (size>0){
    sm.put(1/*how to get a new key*/,aux.iterator().next());
    size--;
  }

return sm;
}

1

There are 1 best solutions below

0
João Maia On

Turns out my interpretation of the problem was off and after half a day trying to solve it understood that my use of the supplier was completely off. What i should have done was cycle through the Map teams.values() and for each Team verify if the number of points already existed as a key on the Map sm. If it existed, i should get the values associated and add the new team name with methods get on sm. If it didn't, using the supplier i should obtain a new list (using the method get on supplier) and add to this list the new team name. finally i should place in sm a new entry with the number of points and the new list (using method put)

Solution:

public static <C extends Collection<String>> SortedMap<Integer, C> toTable(Map<String, Team> teams, Comparator<Integer> cmp,
                                                                               Supplier<C> supplier) {
        SortedMap<Integer, C> sm = new TreeMap<Integer, C>(cmp);
        C newTeam = null;
        for (Team t: teams.values()){
            if(sm.containsKey(t.getPoints())) {
                sm.get(t.getPoints());
                newTeam.add(t.getName());
            }
            else{
                newTeam = supplier.get();
                newTeam.add(t.getName());
                sm.put(t.getPoints(),newTeam);
            }
        }
        return sm;
    }