Java迭代集合

时间:2010-10-15 02:37:20

标签: java collections iterator hashmap

我有一个需要帮助的练习项目。这是一个简单的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,其中包含一个String键(邮件收件人的名字),该值包含该特定收件人的邮件的ArrayList。

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

由于

1 个答案:

答案 0 :(得分:2)

你很亲密。

   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);