views:

41

answers:

1

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

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.

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

Thanks

A: 

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.

Tony Ennis
Wow, this is great. Thanks for your help!
Kenny Powers
Heh, thank me when it works. I didn't compile it, probably full of typos.
Tony Ennis
Do you understand how we're going from treemap -> keyset -> proper map entry -> list -> MailItem? Why did I say `List<MailItem>` instead of `ArrayList<MailItem>` ?
Tony Ennis
Also note the `for` statement idiom...
Tony Ennis
Yep, it does work. The reason I was using iterator was because it seems you can't use foreach on a TreeMap. I'm actually not sure why you used List<MailItem> instead of ArrayList<MailItem>
Kenny Powers
Also, I'm not familiar with this (wrapping String with parentheses): (String) s;
Kenny Powers
Always code to the interface not the implementation. So you put List l = new ArrayList(). Then later on you could change the ArrayList to LinkedList (not that you ever really would), and your code would still run.
bwawok
(String) is casting, saying this object isn't an object, it is a specific type of Object, namely a String.
bwawok