简体   繁体   中英

Java - How do I add a new value to an existing key in a Hash Map. 1 key, multiple values

I am trying to create a method that, when given a key and a value, can access the map via the key and then either add or replace that specific value. My Hash Map is created like so:

public Band(){
    musicians = new HashMap<>();
}

And I can add new entries like so, with band acting as the key:

public void addMapEntry(String band, String name, String instrument, int experience){
    musicians.put(band, new Musician(name, instrument, experience));
}

My new method header look like this:

public void addValue(){ }

I have tried using the put method but I can't get it work as I'd like. I have also tried iterating through the map, but I've only ever used that method to return map objects in a list, whereas I don't want to return anything in this method. I want to be able to send it two arguments (the key and the value) and have it only replace that specific value.

I hope I have been clear in my explanation.

Java Map is single value for each key.

If you need multiple values for a single key, you should make the type a collection of the appropriate type and add your own logic for adding a new value. Your Band class should have methods to add/remove a Musician and handle the details in the private implementation.

public class Band {

   private Map<String, List<Musician>> members = new HashMap<String, List<Musician>>();

   public void addMusician(String key, Musician musician) {
       if (this.members.containsKey(key) {
           List<Musician> musicians = this.members.get(key);
           if (musician != null) {
               musicians.add(musician);
               this.members.put(key, musicians);
           }
       }
   }

   public void removeMusician(String key, Musician musician) {
       // should be clear enough from the add method.
   }
}

I think the most suitable for you is to use Guava Multimap

 ListMultimap<String, String> musicianMap = ArrayListMultimap.create();

Then add as many musicians to your band

musicianMap.put("Beatles", new Musician("Jhon Lennon"));
musicianMap.put("Beatles", new Musician("Paul McCartney"));
musicianMap.put("Beatles", new Musician("Ringo Starr"));
musicianMap.put("Beatles", new Musician("George Harrison"));

And you can pull them all using just key.

musicianMap.get("Beatles")

This will return a list of ["John Lenon", "Paul McCartney", "Ringo Starr"] of course these will objects of class Musician.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM