hashmap - java insert in Map<String, Set<String>> -
in c++ can do:
map<string, set<string>> v; v["aha"].insert("ba");
in java have:
hashmap<string, set<string>> v = new hashmap<string, set<string>>();
how can insert "ba" v["aha"] c++?
yes try this:
set<string> vs = v.get("b"); if (vs == null) vs = new hashset<string>(); vs.add("v"); v.put("b", vs);
but large
if want add set, , allow possibility key/value pair might not yet exist in map, can use computeifabsent
v.computeifabsent("aha", k -> new hashset<string>()).add("ba")
this key in map, , if missing, add new empty set value, can add stuff straight it.
if you're using version of java before java 8, it's little more code:
set<string> s = v.get("aha"); if (s==null) { s = new hashset<string>(); v.put("aha", s); } s.add("ba");
Comments
Post a Comment