有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

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

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

谢谢


共 (1) 个答案

  1. # 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);可以改进