0

Add a method to the MailServer class called printAllMessages, that iterates through the users, prints out each user name, and prints out all the emails associated with that user.

I cannot figure out how to print out the content of the emails, which is in ArrayList form.

Here is my code:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Iterator;
import java.util.HashSet;
import java.util.Set;

/**
 * A simple model of a mail server. The server is able to receive
 * mail items for storage, and deliver them to clients on demand.
 * 
 * @author David J. Barnes and Michael Kölling
 * @version 2011.07.31
 */
public class MailServer
{
    // Storage for the arbitrary number of mail items to be stored
    // on the server.
    private HashMap<String, ArrayList<MailItem>> items;

    /**
     * Construct a mail server.
     */
    public MailServer()
    {
        items = new HashMap<String, ArrayList<MailItem>>();
    }

    /**
     * Return how many mail items are waiting for a user.
     * @param who The user to check for.
     * @return How many items are waiting.
     */
    public int howManyMailItems(String who)
    {
        int count = 0;
        for(String name : items.keySet()) 
        {
            if(who != null) 
            {
                who = formatName(who);
            }
            if(items.containsKey(who))
            {
                count++;
            }
        }
        return count;
    }

    /**
     * Formats the name into lower case.
     * @param who The user to check for.
     */
    private static String formatName(String who)
    {
        if(who.length() > 0)
        {
            return who.toLowerCase();
        }
        return "";
    }

    /**
     * Return the next mail item for a user or null if there
     * are none.
     * @param who The user requesting their next item.
     * @return The user's next item.
     */
    public MailItem getNextMailItem(String who)
    {
        if(who != null)
        {
            who = formatName(who);
        }
        ArrayList<MailItem> mails = items.get((who));
        if(mails == null)
        {
            return null;
        }
        Iterator<MailItem> it = mails.iterator();
        while(it.hasNext()) 
        {
            MailItem item = it.next();
            if(item.getTo().equals(who)) 
            {
                it.remove();
                return item;
            }
        }
        return null;
    }

    /**
     * Return the specified number of mail items for a user or
     * null if there are none.
     * @param who The user requesting their next item.
     * @param howMany The number of mail items requested.
     * @return The user's specified number of next items.
     */
    public ArrayList<MailItem> getNextMailItems(String who, int howMany)
    {
        ArrayList<MailItem> itemsToReturn = new ArrayList<MailItem>();
        if(who != null)
        {
            who = formatName(who);
        }
        ArrayList<MailItem> mails = items.get((who));
        if(mails == null)
        {
            return null;
        }
        Iterator<MailItem> it = mails.iterator();
        while(it.hasNext() && howMany > 0)
        {
            MailItem item = it.next();
            it.remove();
            itemsToReturn.add(item);
            howMany--;
        }
        return itemsToReturn;
    }

    /**
     * Add the given mail item to the message list.
     * @param item The mail item to be stored on the server.
     */
    public void post(MailItem item)
    {
        if(isSpam(item))
        {
            return;
        }
        String who = item.getTo();
        ArrayList<MailItem> mails;
        if(items.containsKey(who))
        {
            mails = items.get(who);
        }
        else
        {
            mails = new ArrayList<MailItem>();
            items.put(who, mails);
        }
        mails.add(item);
    }

    /**
     * Return true if the item is spam; otherwise return false.
     * @param The mail item.
     */
    private boolean isSpam(MailItem item)
    {
        if(item.getSubjectLine().contains("SPAM"))
        {
            return true;
        }
        if (item.getMessage().toLowerCase().contains("viagra"))
        {
            return true;
        }
        return false;
    }

    /**
     * Iterates through the users, prints out each user name, and 
     * prints out all the emails associated with that user.
     */
    public void printAllMessages()
    {
        for(String who : items.keySet())
        {
            ArrayList<MailItem> mails = items.get(who); 
            for(MailItem message : mails)
            {
                System.out.println(who + ": " + mails);
            }

        }
    }
}
import java.util.ArrayList;
/**
 * A class to model a simple email client. The client is run by a
 * particular user, and sends and retrieves mail via a particular server.
 * 
 * @author David J. Barnes and Michael Kölling
 * @version 2011.07.31
 */
public class MailClient
{
    // The server used for sending and receiving.
    private MailServer server;
    // The user running this client.
    private String user;
    private int howMany;

    /**
     * Create a mail client run by user and attached to the given server.
     */
    public MailClient(MailServer server, String user)
    {
        this.server = server;
        this.user = user;
    }

    /**
     * Return the next mail item (if any) for this user.
     */
    public MailItem getNextMailItem()
    {
        return server.getNextMailItem(user);
    }

    /**
     * Return the specified number of mail items (if any)
     * for this user.
     */
    public ArrayList<MailItem> getNextMailItems(int howMany)
    {
        return server.getNextMailItems(user, howMany);
    }

    /**
     * Print the next mail item (if any) for this user to the text 
     * terminal.
     */
    public void printNextMailItem()
    {
        MailItem item = server.getNextMailItem(user);
        if(item == null) 
        {
            System.out.println("No new mail.");
        }
        else 
        {
            item.print();
        }
    }

    /**
     * Send the given message to the given recipient via
     * the attached mail server.
     * @param to The intended recipient.
     * @param message The text of the message to be sent.
     */
    public void sendMailItem(String to, String subjectline, String message)
    {
        MailItem item = new MailItem(user, to, subjectline, message);
        server.post(item);
    }
}
/**
 * A class to model a simple mail item. The item has sender and recipient
 * addresses and a message string.
 * 
 * @author David J. Barnes and Michael Kölling
 * @version 2011.07.31
 */
public class MailItem
{
    // The sender of the item.
    private String from;
    // The intended recipient.
    private String to;
    // The text of the message.
    private String subjectline;
    // The subject line of the message.
    private String message;

    /**
     * Create a mail item from sender to the given recipient,
     * containing the given message.
     * @param from The sender of this item.
     * @param to The intended recipient of this item.
     * @param message The text of the message to be sent.
     */
    public MailItem(String from, String to, String subjectline, String message)
    {
        this.from = from;
        this.to = to;
        this.subjectline = subjectline;
        this.message = message;
    }

    /**
     * @return The sender of this message.
     */
    public String getFrom()
    {
        return from;
    }

    /**
     * @return The intended recipient of this message.
     */
    public String getTo()
    {
        return to.toLowerCase();
    }

    /**
     * @return The subject line of this message.
     */
    public String getSubjectLine()
    {
        return subjectline;
    }

    /**
     * @return The text of the message.
     */
    public String getMessage()
    {
        return message;
    }

    /**
     * Print this mail message to the text terminal.
     */
    public void print()
    {
        System.out.println("From: " + from);
        System.out.println("To: " + to);
        System.out.println("Subject Line: " + subjectline);
        System.out.println("Message: " + message);
    }
}
Unheilig
  • 16,196
  • 193
  • 68
  • 98
Chandler Warren
  • 17
  • 1
  • 1
  • 7
  • 1
    Can you reduce the code and post only [MVCE](http://stackoverflow.com/help/mcve)? Also, where is the data structure that holds all emails for a user. – sam Oct 28 '15 at 23:50
  • Most of the code is valuable to the question at hand. The data structure for a user is held within mails, which is an arraylist. – Chandler Warren Oct 29 '15 at 00:08

1 Answers1

0

I am not sure if I understood your question correctly. I think you have an map with list of emails as values. Here is an simple example that shows how to print hashmap with list as values.

Map<String, List<Integer>> map = new HashMap<String, List<Integer>>() {{
    put("a", Arrays.asList(0,1,2,3,4));
    put("b", Arrays.asList(5,6,7,8,9));
}};

    
for (Map.Entry<String, List<Integer>> entry: map.entrySet()) {
    System.out.println(entry.getKey() + " " + entry.getValue().toString());
}

Output:

a [0, 1, 2, 3, 4]

b [5, 6, 7, 8, 9]

Demo

You can tweak the example based on your requirements.

EDIT: You are receiving the error because you are keySet returns a set of keys. If you only want emails for a specific user, then based on my example, you can use get which wil return the arraylist mapped to that string

System.out.println(map.get("a").toString());

EDIT2: Since MailItem is a object, you can assign the map value to a list. Then you can iterate over the list to print all the email for that particular user.

Simple example:

List<String> list = new ArrayList<String>();
String string = "";
Ideone(String a) { string = a; }

public String getString() {
    return this.string;
}

public static void main (String[] args) throws java.lang.Exception
{
    Ideone idA = new Ideone("a");
    Ideone idB = new Ideone("b");
    
    Map<String,List<Ideone>> map = new HashMap();
    
    map.put("john",new ArrayList<Ideone>(Arrays.asList(idA, idB)));
    
    List<Ideone> stringList = map.get("john");
    
    for (Ideone id: stringList) {
        System.out.println(id.getString());
    }
}

Demo for EDIT2

Community
  • 1
  • 1
sam
  • 2,033
  • 2
  • 10
  • 13
  • What is Entry in this? – Chandler Warren Oct 29 '15 at 01:20
  • It is a HashMap with String keys and an ArrayList of values. When I try to run it, I'm getting an error that java.lang.String cannot be converted to java.util.HashMap> – Chandler Warren Oct 29 '15 at 01:32
  • `public void printAllMessages() { for(HashMap> items : items.keySet()) { System.out.println(entry.getKey() + ": " + entry.getValue().toString()); } }` – Chandler Warren Oct 29 '15 at 01:32
  • @ChandlerWarren entry is just a variable name that I am using to iterate over the map. You are receiving error because you are retrieving `keys` only by using [`keySet()`](http://docs.oracle.com/javase/7/docs/api/java/util/Map.html#keySet()). change that to `items.entrySet()` – sam Oct 29 '15 at 11:22
  • Even with those changes I am getting the same error. – Chandler Warren Oct 29 '15 at 16:03
  • `public void printAllMessages() { for(HashMap> entry : items.entrySet()) { System.out.println(items.get(who).toString()); } }` – Chandler Warren Oct 29 '15 at 16:03
  • @ChandlerWarren What is `MailItem`? Also, if you just want to `get` one value, no need to use a loop – sam Oct 29 '15 at 16:10
  • MailItem is the type for message since that is the class it comes from. The problem is that I am trying to get all the emails sent to one user, so I think I do have to user a loop. – Chandler Warren Oct 29 '15 at 16:38
  • @ChandlerWarren The loop you used is to iterate over the `hashmap`. If you are using `get`, no need to loop over the `map`. Since `MailItem` is an object, you can loop over the map value which is an list and then print using your `getter` Check [here](http://stackoverflow.com/questions/8600724/how-to-iterate-through-list-of-object-arrays) – sam Oct 29 '15 at 16:45
  • I cannot specify "john" like in the example. I just need to be able to print out all of the users that have mail and all of their mail. Will that change things? – Chandler Warren Oct 29 '15 at 17:04
  • @ChandlerWarren john in the example is similar to `who` in your example – sam Oct 29 '15 at 18:27
  • `** * Iterates through the users, prints out each user name, and * prints out all the emails associated with that user. */ public void printAllMessages() { for(String who : items.keySet()) { ArrayList mails = items.get(who); for(MailItem message : mails) { System.out.println(who + ": " + message.toString()); } } }` – Chandler Warren Oct 29 '15 at 20:49
  • That is my new code. I need to create a toString() method that will use a for each loop to get the values from the ArrayList. How do I do that? – Chandler Warren Oct 29 '15 at 20:49
  • @ChandlerWarren Check [here](http://stackoverflow.com/search?q=tostring+override+java) and try to implement based on your requirments. If there is any problem, post a new question and (let me know by commenting here if you want and I will take a look) so future readers don't get confused. – sam Oct 29 '15 at 21:18
  • Do you know how I would get the getNextMailItems() method to return "" when it is empty instead of returning null? I am trying to test it and am getting a null pointer exception every time. By the way, I figured the other out. Thank you! – Chandler Warren Oct 29 '15 at 21:51
  • @ChandlerWarren Check for null before adding to arraylist. If that doesn't resolve your issue, create a new question as it is an different issue than your original question but make sure to check out [this question](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it) – sam Oct 29 '15 at 22:04