user3006513
user3006513

Reputation: 39

How to stop repeated print in java

I am printing items from an ArrayList with this code:

for(int i2 = 0; i2 < a.size(); i2++)
    {
        word2 = a.get(i2);
        for(int j2 = 0; j2 < a.size(); j2++)
        {
            if(word2.equals(a.get(j2)))
            {
                counter++;
            }
        }
        if(counter!=0)
        {
            System.out.println(word2 + " : " + counter);
        }
        counter = 0;
    } 

When I print I don't want to print out the duplicates. As it is now, it will print

Alphabet : 3
Alright : 3
Apple : 3
Alphabet : 3
Alright : 3
Apple : 3
Alphabet : 3
Alright : 3
Apple : 3

I only want it to print

Alphabet : 3
Alright : 3
Apple : 3

How do I make it not print the duplicates? I have to use ArrayList for the assignment

Upvotes: 2

Views: 3128

Answers (3)

David P&#233;rez Cabrera
David P&#233;rez Cabrera

Reputation: 5048

Another Java-8 stream alternative:

This creates a map at collect step: the key is the word (because Function.identity() returns every word) and the value is the frequency (because Collectors.counting() returns every word frequency). And the forEach step just prints every entry "<word>: <word-frequency>"

a.stream().collect(Collectors.groupingBy(
               Function.identity(),
               Collectors.counting()))
          .forEach((word, frequency) -> System.out.println(word+": "+frequency));

Upvotes: 0

Jason C
Jason C

Reputation: 40335

Another option, while performance is not the greatest (although it will be sufficient for your application, and has similar performance characteristics to your current code), is to create a temporary Set to hold a list of unique words, then use Collections.frequency() to count the occurrences in the original list, e.g. with your ArrayList<String> a:

Set<String> unique = new HashSet<String>(a);

for (String word : unique)
    System.out.println(word + " : " + Collections.frequency(a, word));

Or even just:

for (String word : new HashSet<String>(a))
    System.out.println(word + " : " + Collections.frequency(a, word));

The benefit here is short and clear code.

You can use a TreeSet if you want to print the words in alphabetical order, or a LinkedHashSet if you want to print them in the order of first occurrence.

As an aside, the above does not store the counts for later use, which your original code does not do either. However, if you wanted to do this, it's trivial to store the results in a map:

Map<String,Integer> wordCounts = new HashMap<String,Integer>();

for (String word : new HashSet<String>(a))
    wordCounts.put(word, Collections.frequency(a, word));

// wordCounts now contains a map of strings -> counts.    

Upvotes: 2

Brian
Brian

Reputation: 7326

Use a TreeMap<String, Integer> to track word counts

SortedMap<String, Integer> wordFrequencyMap = new TreeMap<String, Integer>();

for (String str : a) {
  if (wordFrequencyMap.containsKey(str)) {
    int strFreq = Integer.intValue(wordFrequencyMap.get(str));
    strFreq++;
    wordFrequencyMap.put(str, new Integer(strFreq));
  }
  else {
    wordFrequencyMap.put(str, new Integer(1));
  }
}

for (String word : wordFrequencyMap.keySet()) {
  System.out.println(word + " : " + wordFrequencyMap.get(word));
}

This data structure will not allow duplicates and it will count the occurrence of each word with only having to traverse the list one time. Since you are using a TreeMap with String keys, it will print the keys in alphabetical order when iterating

Upvotes: 1

Related Questions