0

I fetched some data from DB using and stored it in a list as below:

List<MyObject> list =new ArrayList<MyObject>();

list contains 2 MyObject class's objects.

I have 2 Map implementations:

Map<String,Map<String,Long>> map1 = new HashMap<String,Map<String,Long>>();
Map<String,Long> map2 = new HashMap<String,Long>();

I iterated the list and did the following code

for(myObjectObj   :   list){

      map2.put(myObjectObj.getAction(),myObjectObj.getCount());
      map1.put(myObjectObj.getName(),map2);
}

Final output i wanted was map1 in the following way :

Name1 action1 count1
      action2 count2
Name2 action3 count3
      action4 count4

but with my code i am not getting the desired output.

1
  • Specifying what output you are getting would be a good start. Commented Jul 20, 2012 at 10:19

1 Answer 1

2

In your current version, the data you add to the map2 instance will be actually added to all entries of map1, as the map2 reference is common to all the map1 instances.

Given that you want a new nested map for every entry in your list, you need to get or instantiate a new map2 within the loop:

for(myObjectObj   :   list){ 
      String key = myObjectObj.getName();
      Map<String,Long> map2 = map1.get(key);
      if (map2 == null) {
          map2 = new HashMap<String,Long>();
          map1.put(key, map2);
      }
      map2.put(myObjectObj.getAction(),myObjectObj.getCount());
}
Sign up to request clarification or add additional context in comments.

4 Comments

actually you'd need to test to see if the key already existed in map1 first, and if it did, add the new entry to that map - your version will not do that..
@Nim given that the data is coming from the db, I'm assuming that the map1 key is the pk for the object, so checking should not be necessary. In any case, I think this answer solves the main issue of the OP; cfr: using a shared nested map instance. Other conditions based on OP's requirements are his/her responsibility.
@Nim oh, I see. You're right. A look up is necessary. Or a google multimap to make things easier.
@Nim, thanks for the observation. It should be corrected now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.