0

I'm reading emails using JavaMail API and adding each message (along with sender, sent date etc) to a LinkedHashMap. Next I'm adding the LinkedHashMap to an ArrayList of LinkedHashMaps. However, the odd thing is that the entire Hashmapis being overwritten by the last entry.

I have the following code:

private ArrayList<LinkedHashMap<String, String>> readAllMsgsFromOutlook() throws FileNotFoundException, IOException, MessagingException
    {

        LinkedHashMap<String, String> msgsLinkedHashMap = new LinkedHashMap<String, String>();
        ArrayList<LinkedHashMap<String, String>> msgsLinkedHashMapAsArrayList = new ArrayList<LinkedHashMap<String, String>>();

        //String host = "smtp-mail.outlook.com";

        String emailID = ..getEmail();
        String password = ..getPassword();
        Properties props = new Properties();

        props.setProperty("mail.store.protocol", "imaps");


        try {
            Session session = Session.getInstance(props, null);

            Store store = session.getStore("imaps");
            store.connect("imap-mail.outlook.com", emailID, password);
            Folder inboxFolder = store.getFolder("INBOX");
            UIDFolder UID = (UIDFolder)inboxFolder;

            Message[] msgs = null;


            Flags seen = new Flags(Flags.Flag.SEEN);
            FlagTerm unseenFlagTerm = new FlagTerm(seen, false);
            msgs = inboxFolder.search(unseenFlagTerm);  


            System.out.println("Number of New Emails in Inbox: " + msgs.length + "\n");



            String senderAsString = "";
            String sentDateAsString = "";
            String subjectAsString = "";
            String contentAsString = "";
            String UIDAsString = "";


            for (int msgCounter = 0; msgCounter < msgs.length; msgCounter++) 

            {

                System.out.println("Email #: " + (msgCounter + 1) + "\n");

                Message msg  = msgs[msgCounter];
                long UIDAsLong = UID.getUID(msg);

                Object content = msg.getContent();  


                if (content instanceof String)  
                {  
                    System.out.println("Email is instance of String: \n");


                    Address[] sender = msg.getFrom();



                    senderAsString = sender[0].toString();
                    System.out.println("SENDER: " + senderAsString);
                    sentDateAsString = msg.getSentDate().toString();
                    System.out.println("SENT_DATE: " + sentDateAsString);

                    subjectAsString = msg.getSubject().toString();
                    System.out.println("SUBJECT: " + subjectAsString);
                    contentAsString = (String)content; 
                    System.out.println("CONTENT: " + contentAsString);

                    UIDAsString = String.valueOf(UIDAsLong);

                    System.out.println("UID: " + UIDAsString);


                    System.out.println("\n");



                }  
                else if (content instanceof Multipart)  
                {  
                    System.out.println("Email is instance of Multipart");

                    Multipart mp = (Multipart)content;  
                    BodyPart bp = mp.getBodyPart(0);
                    Address[] sender = msg.getFrom();
                    sentDateAsString = msg.getSentDate().toString();
                    subjectAsString = msg.getSubject();
                    contentAsString = bp.getContent().toString();

                    senderAsString = sender[0].toString();
                    System.out.println("SENDER: " + senderAsString);


                    System.out.println("SENT DATE: " + sentDateAsString);


                    System.out.println("SUBJECT: " + subjectAsString);
                    System.out.println("CONTENT: " + contentAsString);
                    UIDAsString = String.valueOf(UIDAsLong);

                    System.out.println("UID: " + UIDAsString);

                    System.out.println("\n");


                }



                msgsLinkedHashMap.put("sender", senderAsString);
                msgsLinkedHashMap.put("sentDate", sentDateAsString);
                msgsLinkedHashMap.put("subject", subjectAsString);
                msgsLinkedHashMap.put("content", contentAsString);
                msgsLinkedHashMap.put("UID", UIDAsString);



                msgsLinkedHashMapAsArrayList.add(msgsLinkedHashMap);



        }



        } catch (Exception mex) {
            // TODO Auto-generated catch block
            mex.printStackTrace();
        }

At this point the content that is added seems to be correct. For example, if I had 24 messages and the content was "msg1", "msg2", "msg3" etc then this system prints out the correct content.

However when I loop through the HashMap after the following closing brackets all I get is the 24th element. In other words, the system will always print "msg24" even for the first 23 elements in list in the following code:

        for (int arrayListCounter = 0; arrayListCounter < msgsLinkedHashMapAsArrayList.size(); arrayListCounter++) {

            LinkedHashMap<String, String> singleHashmapInArrayList = msgsLinkedHashMapAsArrayList.get(arrayListCounter);

            String content = singleHashmapInArrayList.get("content");

            System.out.println(">>> " + arrayListCounter + " : " + content);

// For some reason content is always equal to msg24 instead of msg1, msg2, msg3 etc. It seems like the 24th element is replacing all previous elements. But why? }

        return msgsLinkedHashMapAsArrayList;

    }

I've been trying to figure out the problem for hours.

What am I doing wrong?

ee clipse
  • 245
  • 1
  • 3
  • 14

1 Answers1

2

As you assigned msgsLinkedHashMap variable outside the loop you're always editing the same object and keep adding it's instance to the list. The solution is to move

Map<String, String> msgsLinkedHashMap = new LinkedHashMap<String, String>();

inside your for loop so you'll be creating new instance of Map on each iteration.

Dmitry Smorzhok
  • 635
  • 11
  • 21