Wednesday, August 14, 2013

How To Find Number Of Occurrence Of An Object In List



The frequency(Collection<?>, Object) method is used to get the number of occurrence of an elements in the specified collection.

Declaration
declaration of method -  java.util.Collections.frequency().

public static int frequency(Collection<?> c, Object o)

Parameters

Collection<?> c  -  Pass the object of collection in which to determine the frequency of o.

Object o  -  Pass the object whose frequency is to be determined.


Example :

*********************************************************************************
package org.javaIsEasy.collectionPrograms;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;

public class FrequencyExample {
 public static void main(String[] args) {
  ArrayList<String> programmingLanguageList = new ArrayList<String>();
  programmingLanguageList.add("PHP");
  programmingLanguageList.add(".NET");
  programmingLanguageList.add("PERL");
  programmingLanguageList.add("JAVA");
  programmingLanguageList.add("PERL");
  programmingLanguageList.add("PYTHON");
  programmingLanguageList.add("PERL");

  System.out.println("Display List Of Programming Language\n");
 
  Iterator<String> it = programmingLanguageList.iterator();
 
  while (it.hasNext()) {
   System.out.println(it.next());
  }
 
  int occurrences_Of_PERL = Collections.frequency(programmingLanguageList, "PERL");

  System.out.println("Display occurrences of 'PERL'---->"+ occurrences_Of_PERL);
 }
}

*********************************************************************************


OUTPUT :

*********************************************************************************
Display List Of Programming Language

PHP
.NET
PERL
JAVA
PERL
PYTHON
PERL
Display occurrences of 'PERL'---->3

*********************************************************************************