0

I am getting Employee DOB and Department name from database. Then I am processing DOB to get the age using.

Map<String,ArrayList<Integer>> emp = new HashMap<String,ArrayList<Integer>>()

          while(rs.next()){ 

            //rs is resultset of DB Query               
            String dob = rs.getString(1);
            //Calculating age in variable age
        age = age of employee from DOB

    emp = addIntoMap(emp,rs.getString(2),age);

        }

    public Map<String, List<Integer>> addIntoMap(Map<String, List<Integer>> emp, String key, Integer value) {
        List<Integer> list = emp.get(key);
        if (list == null) {
            list = new ArrayList<Integer>();
            emp.put(key, list);
        }
        list.add(value);
    return emp;

    }

Now I want to construct and HashMap of type <Department_Name,ArrayList<Age of emplyees>>. Here the dperamtnet_name is the key and for each key I want list of age of employees

I know that using Map<String,ArrayList<Integer>> emp = new HashMap<String,ArrayList<Integer>>() I can construct a multi hashmap but how do I put the age values for each key?

1 Answer 1

1

Create your own method to add the elements in the map:

public void addIntoMap(Map<String, List<Integer>> emp, String key, Integer value) {
    List<Integer> list = emp.get(key);
    if (list == null) {
        list = new ArrayList<Integer>();
        emp.put(key, list);
    }
    list.add(value);
}

If you don't want/need to deal with these problems, use MultiMap from Guava.

Sign up to request clarification or add additional context in comments.

11 Comments

Is innerMap a typo? Did you mean emp?
@Joffrey code fixed. It was adapted from a previous answer of me.
@LuiggiMendoza I have updated the code above.Is it correct and will it work?
@user2966197 why are you creating the Map on every iteration? If you do that, you will lose the data per iteration. Move the Map declaration above the while.
@LuiggiMendoza sorry that was a typo. Is it correct now?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.