0

So I need to compare two different ArrayLists elements. If the element from the first ArrayList(tweets) does not match any from the second(hashTags) I want to add the element(from tweets) to the second ArrayList(hashTags)

Here is my code thus far:

package edu.bsu.cs121.albeaver;

import java.util.*;

public class HashTagCounter {
    public static void main(String args[]) {
        System.out
                .println("Please tweet your tweets,and type 'done' when  you are done.");
        Scanner twitterInput = new Scanner(System.in);

        ArrayList<String> tweets = new ArrayList<String>();
        ArrayList<String> hashTags = new ArrayList<String>();

        while (true) {
            String tweet = twitterInput.next();
            tweets.add(tweet);
            if ("done".equals(tweet))
                break;
        }

        System.out.println(tweets);
        twitterInput.close();
        int count = 0;

        for (String tweet : tweets) {
            if (tweet.contains("#") && count == 0) {
                hashTags.add(tweet);
                hashTags.add(1, "");
                count++;
            } else if (tweet.contains("#")) {
                for (String hashTagged : hashTags) {
                    if (tweet.equalsIgnoreCase(hashTagged) != true) {
                        hashTags.add(hashTagged);
                    }
                }
            }
        }

        System.out.println(hashTags);
        System.out.println("Number of unique '#' used is: "
                + (hashTags.size() - 1));

    }
}

(edit)I seem to get a 'java.util.ConcurrentModificationException' error. Thank you for any and all help:)

2 Answers2

2
    for (String hashTagged : hashTags) {
                        if (tweet.equalsIgnoreCase(hashTagged) != true) {
                            hashTags.add(hashTagged);
  -----------------------------^
                        }
                    }

The issue is while iterating the hashTags list you cant update it.

Kick
  • 4,823
  • 3
  • 22
  • 29
1

You are getting java.util.ConcurrentModificationException because you are modifying the List hashTags while you are iterating over it.

for (String hashTagged : hashTags) {
    if (tweet.equalsIgnoreCase(hashTagged) != true) {
        hashTags.add(hashTagged);
    }
}

You can create a temporary list of items that must be removed or improve your logic.

Trein
  • 3,658
  • 27
  • 36