如何将值列表合并到
key
中的相同HashMap
?
如果我使用上述逻辑,我将得到以下结果作为输出:
{Adam=[[Subject, ComputerScience], [Subject, ComputerScience]]}
但是我必须像下面的结果一样merge,是否可以将值列表附加到同一个key?
{Adam=[Subject, ComputerScience, Subject, ComputerScience]}
public class DemoMap {
public static void main(String[] args) {
ArrayList<String> mngrList1 = new ArrayList<>();
mngrList1.add("Jay");
mngrList1.add("Aaron");
// Adam is Senior Manager who has the list of managers under him
HashMap<String, ArrayList<String>> tmeMap = new HashMap<>();
tmeMap.put("Adam", mngrList1);
ArrayList<Object> emailContent = new ArrayList<>();
emailContent.add("Subject");
emailContent.add("ComputerScience");
HashMap<String, ArrayList<Object>> mngrMap = new HashMap<>();
mngrMap.put("Jay", emailContent);
mngrMap.put("Aaron", emailContent);
// Each manager will have the email content
ArrayList<Object> collectionOfManagerContent = new ArrayList<>();
for (Map.Entry<String,ArrayList<Object>> emailEntry : mngrMap.entrySet()) {
collectionOfManagerContent.add(emailEntry.getValue());
}
// Our goal is to show the manager's content to Senior Project manager
HashMap<String, ArrayList<Object>> tmeEmailMap1 = new HashMap<>();
for (Map.Entry<String,ArrayList<String>> emailEntry : tmeMap.entrySet()) {
emailEntry.getValue();
tmeEmailMap1.put(emailEntry.getKey(), collectionOfManagerContent);
}
System.out.println(tmeEmailMap1.toString());
}
}
使用 addAll() 将 ArrayList 的所有元素添加到另一个 ArrayList 中
for (Map.Entry<String,ArrayList<Object>> emailEntry : mngrMap.entrySet()) {
collectionOfManagerContent.addAll(emailEntry.getValue());
}