2010-10-15 161 views
2

我有一个实践项目,我需要帮助。这是一个简单的MailServer类。下面的代码:Java迭代集合

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 
     } 
    } 
} 

我有一个包含一个String键(邮件收件人的名字)一个HashMap和值包含邮件的该特定收件人的ArrayList。

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

谢谢

回答

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);可以得到改善。

+0

哇,这太好了。谢谢你的帮助! – 2010-10-15 03:04:11

+0

嘿,当它工作时,谢谢我。我没有编译它,可能有很多拼写错误。 – 2010-10-15 03:05:57

+0

你知道我们如何从树图 - >键集 - >正确的地图项 - >列表 - > MailItem?我为什么说'列表'而不是'ArrayList '? – 2010-10-15 03:07:38