D.A.G.D D.A.G.D - 7 months ago 54
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");


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])));