【问题标题】:Java Iterate Over CollectionJava 迭代集合
【发布时间】:2011-04-25 17:49:37
【问题描述】:

我有一个需要帮助的练习项目。这是一个简单的 MailServer 类。代码如下:

import java.util.ArrayList;
import java.util.List;
import java.util.Iterator;
import java.util.HashMap;
import java.util.TreeMap;
import java.util.Collection;
import java.util.Map;

public class MailServer
{
    private HashMap<String, ArrayList<MailItem>> items;

    // mail item contains 4 strings:
    // MailItem(String from, String to, String subject, String message)

    public MailServer()
    {
        items = new HashMap<String, ArrayList<MailItem>>();
    }

    /**
     *
     */
    public void printMessagesSortedByRecipient()
    {
       TreeMap sortedItems = new TreeMap(items);

       Collection c = sortedItems.values();

       Iterator it = c.iterator();

       while(it.hasNext()) {
            // do something
       }
    }
}

我有一个 HashMap,其中包含一个字符串键(邮件收件人的姓名),该值包含该特定收件人的邮件的 ArrayList。

我需要对 HashMap 进行排序,并显示每个用户的姓名、电子邮件主题和消息。我在这部分遇到了问题。

谢谢

【问题讨论】:

    标签: java collections iterator hashmap


    【解决方案1】:

    你已经接近了。

       TreeMap sortedItems = new TreeMap(items);
    
       // keySet returns the Map's keys, which will be sorted because it's a treemap.
       for(Object s: sortedItems.keySet()) {
    
           // Yeah, I hate this too.
           String k = (String) s;
    
           // but now we have the key to the map.
    
           // Now you can get the MailItems.  This is the part you were missing.
           List<MailItem> listOfMailItems = items.get(s);
    
           // Iterate over this list for the associated MailItems
           for(MailItem mailItem: listOfMailItems) {
              System.out.println(mailItem.getSomething());
              }
           }
    

    但是,您需要清理一些杂物 - 例如,TreeMap sortedItems = new TreeMap(items); 可以改进。

    【讨论】:

    • 哇,这太棒了。感谢您的帮助!
    • 嘿,谢谢我。我没有编译,可能全是错别字。
    • 你了解我们是如何从树状图 -> 键集 -> 正确的地图条目 -> 列表 -> 邮件项开始的吗?为什么我说List&lt;MailItem&gt;而不是ArrayList&lt;MailItem&gt;
    • 是的,它确实有效。我使用迭代器的原因是因为您似乎不能在 TreeMap 上使用 foreach。我实际上不确定您为什么使用 List 而不是 ArrayList
    • 另外,我不熟悉这个(用括号包裹字符串): (String) s;
    猜你喜欢
    • 1970-01-01
    • 2015-08-17
    • 2010-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多