[java] Maps and Sets

Started by
4 comments, last by mattd 14 years, 2 months ago
Map<String, Set<String>> mainMap; Set<String> valueSet; Set<String> keySet; mainMap = new HashMap<String, Set<String>>(); valueSet = new HashSet<String>(); keySet = new HashSet<String>(); The values in mainMap are:- {"e","f","h","l", "n","o","s","t","u","v"}, {"f","g","h","i","j","k","l","m","v","w","x","y","z"}, {"b","c","d","e","j","k","l","mm","n","o","p","w","x","y"}, The Keys are:- {"Member1", "Member2", "Member3"} I am trying to get the values from mainMap and put them into the set valueSet. I can get the keys into the keySet easily enough but I always end up with only the last set of values in valueSet. valueSet should eliminate any duplicate entries automatically as per the set rules. Below is my code:-

public void Extract()
{
   keySet = mainMap.keySet();
                 
   for (String eachSetValue : mainMap.keySet())
   {
      valueSet = mainMap.get(eachSetValue);
                          
   }
}

In keySet I end up with {"Member1", "Member2", "Member3"}. However in valueSet I end up with, {"b","c","d","e","j","k","l","mm","n","o","p","w","x","y"}. It's like valueSet is being over-written with each value set but I cannot work out how to fix it.
Advertisement
Here:
valueSet = mainMap.get(eachSetValue);

you assign the value of each value to valueSet. What you really want to do is add each of the values to valueSet. Try using the addAll() method.
Thanks that has fixed it nicely :) I did try using the add() function initially but that didn't compile. Should of probably checked the JavaDocs :).
Another quick question,

I've created another map, switchMap = new HashMap<String, Set<String>>();

The key of which is now the valueSet, done by the top for loop in the code below. What I'm trying to do in the nested for loop below is for each member in memberSet, for each value in that members mainMap, add the member, so switchMap ends up like,

Key Values
"e" { "Member1", "Member3" }
"f" { "Member2" }
"h" { "Member2", "Member3" }

This is confusing enough to word so if this makes no sense I understand.

public void doSwitch(){   for (String eachValue : valueSet)   {      switchMap.put(eachValue, new TreeSet<String>());   }         for (String eachMember : memberSet)   {      for (String eachValue : mainMap.get(mainMap.values()))      {         switchMap.add(mainMap.get(eachMember) );      }   }}
Anyone?
You said you'd understand :]

Your description is confusing.

At least it's easy to see that your code is confused. Check out the body of the inner loop:

switchMap.add(mainMap.get(eachMember) );

This only depends on three variables, switchMap, mainMap, eachMember, of which the first two don't change, and the last only changes in the outer loop. So something is definitely fishy here.

Try describing what you're trying to do in more concrete terms, or provide sample inputs and the desired output.

This topic is closed to new replies.

Advertisement