2010-10-15 172 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