【问题标题】:how to merge the list of values to the same Key in hashmap?如何将值列表合并到哈希图中的相同键?
【发布时间】:2020-07-18 12:10:28
【问题描述】:

如何将值列表合并到 hashmap 中的同一个 Key?
如果我使用上述逻辑,我将得到低于结果的输出 {Adam=[[学科,计算机科学],[学科,计算机科学]]}

但我必须像下面的结果一样合并,是否可以将值列表附加到同一个键?

{Adam=[Subject, ComputerScience,Subject, ComputerScience]}

    public class DemoMap {
        
        public static void main(String[] args) {
            
            HashMap<String, ArrayList<String>> tmeMap = new HashMap<>();
            HashMap<String, ArrayList<Object>> mngrMap = new HashMap<>();
            ArrayList<Object> emailcontent = new ArrayList<>();
             ArrayList<String> mngrList1 = new ArrayList<>();
             mngrList1.add("Jay");
             mngrList1.add("Aaron");
             tmeMap.put("Adam", mngrList1);
        
     //Adam is Senior Manager who has the list of managers under him
 
            emailcontent.add("Subject");
            emailcontent.add("ComputerScience");
            
            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 Target 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());
            
        }
    
    }

【问题讨论】:

    标签: java arraylist data-structures hashmap


    【解决方案1】:

    使用addAll()将ArrayList的所有元素添加到另一个ArrayList中

    for (Map.Entry<String,ArrayList<Object>> emailEntry : mngrMap.entrySet()) {
        collectionOfManagerContent.addAll(emailEntry.getValue());
    }
    

    【讨论】:

      猜你喜欢
      • 2013-02-24
      • 2020-11-16
      • 1970-01-01
      • 2018-06-10
      • 1970-01-01
      • 2015-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多