Java 迭代集合

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3939092/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 04:02:56  来源:igfitidea点击:

Java Iterate Over Collection

javacollectionsiteratorhashmap

提问by Kenny Powers

I have a practice project which I need help with. It's a simple MailServer class. Here's the code:

我有一个需要帮助的练习项目。这是一个简单的 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
       }
    }
}

I have a HashMap which contains a String key (mail recipient's name) and the value contains an ArrayList of the mail for that particular recipient.

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

I need to sort the HashMap, and display the each user's name, email subject, and message. I'm having trouble with this section.

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

Thanks

谢谢

采纳答案by Tony Ennis

You're close.

你很接近。

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

You'll have some cruft to clean up however - for instance, the TreeMap sortedItems = new TreeMap(items);can be improved.

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