簡體   English   中英

向HashMap添加元素 <String, List> -.containsKey()始終返回false

[英]Add elements to HashMap<String, List> - .containsKey() always returns false

我有郵件地址的List<HashMap>以及用戶ID(列表中的每個條目看起來像: id123mail"john@doe.com" )。

我想制作一個HashMap ,其中的每個鍵都是電子郵件地址的域名,值是來自該域的電子郵件列表:

"foo.com":
  [1]
      id: 123,
      mail: a@foo.com
  [2]
      id: 345
      mail: b@foo.com
"bar.com":
  [1]
      id: 787,
      mail: a@bar.com
  [2]
      id: 456
      mail: b@bar.com

為此,我要做下面的事情。 問題是,當我嘗試添加新列表條目以將現有條目添加到domain條目時,java將新記錄添加到sortedAddresses而不是使用當前記錄。 我的預測是containsKey()方法始終返回false。

HashMap<String, List> sortedAddresses = new HashMap<String, List>();

        for(HashMap<String, String> r : this.lightUsersList){

            String mail = r.get("email");
            Integer uid = Integer.parseInt(r.get("id"));


            try{
                String[] mailSplit = mail.split("@");
                String domain = mailSplit[1];

                //if domain key doesn't exist, add it to hashmap
                if(!sortedAddresses.containsKey(domain)){
                    List<HashMap> domainAddr = new ArrayList<HashMap>();
                    sortedAddresses.put(domain, domainAddr);
                }

                List<HashMap> domainAddr = sortedAddresses.get(domain);
                sortedAddresses.remove(domain);
                domainAddr.add(r);
                sortedAddresses.put(domain, domainAddr);

            }
            catch(Exception e){
                //to be implemented
                System.out.println("Nie udalo sie dodac adresu " + mail + " do tablicy domenowej (" + e.getMessage() + ")");
            }



                //displaying hashmap summary (source from another SO thread)
                Iterator it = sortedAddresses.entrySet().iterator();
                while (it.hasNext()) {
                    Map.Entry pairs = (Map.Entry)it.next();
                    System.out.println(pairs.getKey() + " = " + sortedAddresses.get(pairs.getKey()).size());
                    it.remove(); // avoids a ConcurrentModificationException
                } 
        }

我得到的輸出:

foo = 1
bar = 1
foo = 1
bar = 1

應該:

foo = 2
bar = 2

好吧,看來我看錯了。 當然, Iterator部分應該在for循環之后。 我的錯。 討厭星期一。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM