Java迭代在集合 [英] Java Iterate Over Collection

查看:107
本文介绍了Java迭代在集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个练习项目,我需要帮助。这是一个简单的MailServer类。下面是代码:

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

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。

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进行排序,并显示每个用户的姓名,电子邮件主题和消息。

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

感谢

推荐答案

您已关闭。

   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); 可以改进。

这篇关于Java迭代在集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆