Search code examples
javadictionarytreeset

Updating a Set from a Map argument in Java


I have this school question:

The method should returns no value but should take as its argument a map whose keys are strings and whose values are integers. The strings represent person numbers and the integers the respective sales figures. The map entries do not need to be in any particular order.

For each Person in personSet your method should check whether its personNumber is one of the keys in the map. If so, the sales for that Person should be increased by the map value corresponding to that key.

This is the code i got, obviously it's incorrect, any pointers?

public void updatePersons (Map<String, Integer> pers)
   {
     for (Persons all : personSet)
     {
        if (all.getPersonNumber().equals(pers.keySet()))
        {
          personSet.add(pers);
        }
     }
   }

Solution

  • Since a lot of code is missing I'm working on some assumptions:

    If you want to update the reference number of the persons in the set based on the map you can do it like this:

    for (Persons person: personSet) {
      Integer reference = pers.get( person.getPersonNumber() );
      if( reference != null ) {
        person.setReference( reference );
      }
    }
    

    You iterate over all persons and query the map for the value associated with the person number. If such a value exists you update the person and go on with the next person.

    Note that if the reference number is used to sort the set you'd have to remove and reinsert the person to preserve order.