for loop - How to stop repeated print in java -


i printing items arraylist 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 print don't want print out duplicates. now, print

alphabet : 3 alright : 3 apple : 3 alphabet : 3 alright : 3 apple : 3 alphabet : 3 alright : 3 apple : 3 

i want print

alphabet : 3 alright : 3 apple : 3 

how make not print duplicates? have use arraylist assignment

another option, while performance not greatest (although sufficient application, , has similar performance characteristics current code), create temporary set hold list of unique words, use collections.frequency() count occurrences in original list, e.g. arraylist<string> a:

set<string> unique = new hashset<string>(a);  (string word : unique)     system.out.println(word + " : " + collections.frequency(a, word)); 

or just:

for (string word : new hashset<string>(a))     system.out.println(word + " : " + collections.frequency(a, word)); 

the benefit here short , clear code.

you can use treeset if want print words in alphabetical order, or linkedhashset if want print them in order of first occurrence.

as aside, above not store counts later use, original code not either. however, if wanted this, it's trivial store results in map:

map<string,integer> wordcounts = new hashmap<string,integer>();  (string word : new hashset<string>(a))     wordcounts.put(word, collections.frequency(a, word));  // wordcounts contains map of strings -> counts.     

Comments

Popular posts from this blog

css - I want to align grid in center -

Contact Form PHP Email Script -

python - SWIG function not printing output -