Java Collection How to - Check value frequency with Collections.frequency








Question

We would like to know how to check value frequency with Collections.frequency.

Answer

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
//from   ww  w .  j  a va  2s  .co  m
public class Main {
    public static void main(String[] args) {
        List<Integer> values = Arrays.asList( 5, 0, 0, 2 );
        int occurrences = Collections.frequency(values, 0);
        System.out.println("occurrences of zero is " + occurrences);
        
        occurrences = Collections.frequency(values, 5);
        System.out.println("occurrences of 5 is " + occurrences);
    }
}

The code above generates the following result.