Monday, November 11, 2013

Count number of duplicate elements in ArrayList objects using Collections API?


Usage of Collections:

Suppose we have an ArrayList of characters / words which are repeated multiple times, And we want to count number of occurrences of each character / word..

We use only collections API.

Take an Example class

Test.java
-----------
import java.util.*;
public class Test{

        public static void main(String ar[]){

                ArrayList al=new ArrayList(); //It allows duplicates
                        al.add("a");
                        al.add("b");
                        al.add("c");
                        al.add("a");
                        al.add("b");
                        al.add("a");

                Set alSet=new HashSet(al); // no duplicates allowed in set, we get uniques

                        for(String element:alSet){ //using for-each loop
                                  int count=Collections.frequency(al,element); // this method counts the occurrences
                                 System.out.println(element+" repeated "+count+" times");
                        }//end for
        }//end main
}//end class



This is one of many methods,,

And similarly we can use Map object to count repeated characters/words..... Will be continued 

No comments:

Post a Comment