Tuesday, June 10, 2014

Count occurrence of an element

Write a program to count the total number of duplicated entries in a List.

For Example :
Input List of countries : japan,usa,uae,japan,uae,usa,australia
Expected output:
japan:2
usa:2
uae:2
australia:1

Solutions:

Solution 1:
1) Java API provides a class called Collections. This class contains static utility methods for manipulating collections. It provides a static method for counting the number of elements in specified collection, as you can see below for more information. 

static intfrequency(Collection<?> c, Object o)
 Returns the number of elements in the specified collection equal to the specified object.
     c - the collection in which to determine the frequency of o
     o - the object whose frequency is to be determined

// CountDuplicates.java
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

public class CountDuplicates {
   public static void main(String[] args) {
      String[] listOfArray = 
      { "japan", "usa", "uae", "japan", "uae", "usa", "australia" };
      List list = Arrays.asList(listOfArray);
      System.out.println("Frequency of each country ");
      Set uniqueSet = new LinkedHashSet(list);
      for (String countryName : uniqueSet) {
      System.out.println(countryName + ": " 
      + Collections.frequency(list, countryName));
      }
   }
}
//Output::
//Frequency of each country 
//japan: 2
//usa: 2
//uae: 2
//australia: 1

Solution 2:
// CountDuplicates1.java
import java.util.LinkedHashMap;
import java.util.Map.Entry;
import java.util.Map;

public class CountDuplicates1 {
   public static void main(String[] args) {
      String[] listOfArray = 
      { "japan", "usa", "uae", "japan", "uae", "usa", "australia" };
      Map<String, Integer> map = new LinkedHashMap<String,Integer>();
      for( String countryName : listOfArray){
          int count = 0;
          if(map.get(countryName) != null){
               count = map.get(countryName);
          }
          map.put(countryName, count+1);
      } 
      for (Entry countryEntry : map.entrySet()) {
          System.out.println(countryEntry.getKey()+ ": " 
         + countryEntry.getValue() );
      }
   }
}
//Output::
//Frequency of each country 
//japan: 2
//usa: 2
//uae: 2
//australia: 1

No comments:

Post a Comment