tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 Java > Collections > Collection Frequency

Collection Frequency 

The following example shows how to use Collections.frequency API. It returns the count of elements in the collection equal to user given object.

File Name  :  
com/bethecoder/tutorials/utils/collections/Frequency.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.tutorials.utils.collections;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;


public class Frequency {

  /**
   @param args
   */
  public static void main(String[] args) {
    
    List<Integer> intList = Arrays.asList(new Integer [] {
      23456,
      2345,
      234,
      23,
      2
    });
    
    System.out.println("List : " + intList);
    System.out.println();
    
    print(intList, 2);
    print(intList, 3);
    print(intList, 4);
    print(intList, 5);
    print(intList, 6);
    print(intList, 8);
  }
  
  private static void print(List<Integer> intList, Integer val2Check) {
    System.out.println("Frequency of '" + val2Check + "' : " 
        Collections.frequency(intList, val2Check));
  }
}
   

It gives the following output,
List : [2, 3, 4, 5, 6, 2, 3, 4, 5, 2, 3, 4, 2, 3, 2]

Frequency of '2' : 5
Frequency of '3' : 4
Frequency of '4' : 3
Frequency of '5' : 2
Frequency of '6' : 1
Frequency of '8' : 0



 
  


  
bl  br