Stas
Stas

Reputation: 695

Java set collection clarification

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?

Upvotes: 1

Views: 57

Answers (1)

Joe C
Joe C

Reputation: 15704

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")

Upvotes: 5

Related Questions