D.A.G.D D.A.G.D - 1 year ago 138
Java Question

Adding an element into a HashSet inside a HashMap Java

I have this problem which I looked for into the net and I could be helped... I also looked other Questions and they didnt work i dont know why... So I need your help....

So this is a field in which I create the HashMap:

private HashMap <String,HashSet<String>> userBuisness = new HashMap <String,HashSet<String>>();

And this is my try to add an element (i take a line from a file, i split it and then i add these elements into my HashMap):

String output = inputReader.nextLine();
String fields[] = output.split("\t");

Answer Source

As @AndyTurner said in a comment:

fields[1] is a String, not a HashSet<String>. You can build the latter using new HashSet<>(Arrays.asList(fields[1])).

But there are other issues with this snippet too. It would be better to rewrite like this, pay close attention to every little detail that I changed:

private Map<String, Set<String>> userBusiness = new HashMap<>();


String[] fields = output.split("\t");
userBusiness.put(fields[0], new HashSet<>(Collections.singletonList(fields[1])));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download