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?
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.