1

I was thinking of creating a list with keys and values in java and decided to create something like

private static HashMap<String, Set<String>> battleTanks = new HashMap<String, Set<String>>();

then i was trying to add a few values there like battleTanks.put("keytest1", "valuetest1")

But it's giving me an error like

The method put(String, Set) in the type HashMap> is not applicable for the arguments (String, String)

so how can i add those values?

Narendra
  • 1,511
  • 1
  • 10
  • 20
Stas
  • 605
  • 6
  • 21
  • 2
    Given then value is a `Set`, why would `put` with a value as a `String` work? Think it through - this will be a valuable lesson. Hint: you need [`Map.computeIfAbsent`](https://docs.oracle.com/javase/8/docs/api/java/util/Map.html#computeIfAbsent-K-java.util.function.Function-). – Boris the Spider Mar 24 '18 at 10:22
  • you are passing string as the value but its expecting a `set` that is why you are facing this issue. – prabhat mishra Mar 24 '18 at 10:25

1 Answers1

5

What you need to be doing is adding a Set as the value of your Map.

The computeIfAbsent method is a clean way of doing this, as it will either get the set that's already in the map for your key, or create a new one if it's not already there:

battleTanks.computeIfAbsent("keytest1", k -> new HashSet<>()).add("valuetest1")
Joe C
  • 15,324
  • 8
  • 38
  • 50
  • 1
    I like to use `__` for uneeded parameters. It's a bit of a [cludge](https://stackoverflow.com/a/37597939/2071828) but makes the intent clear. – Boris the Spider Mar 24 '18 at 10:25
  • 1
    @BoristheSpider I don't like because that's against the Java way. If it was the Java way, they would never have deprecated `_` (only 1 underscore). – Olivier Grégoire Mar 24 '18 at 10:27
  • @OlivierGrégoire see Holger's comment on my link - the whole _reason_ that `_` was disallowed was so that it could become a throwaway later. In either case, Holger's opinion holds a lot of weight on the "Java way". I shortly, I strong disgree with your assertion about the "Java way", whatever that might be. – Boris the Spider Mar 24 '18 at 10:29