How to get an Object frequency in an ArrayList

The number of times an Object is in a ArrayList can be processed using Collection.frequency method.


int nb = Collections.frequency( list, "String" );

Here is an example the creates a list with several values that are identical. The example counts the number of time a value is defined in the list using 2 methods. The first one is using Collections.frequency. The second one is for Java 8 and up and uses Lambda to filter the List and then counts the number of values left.

Create the following java file:

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

public class CollectionFrequency {

    public static void main(String[] argv) {
	List<String> list = Arrays.asList("a", "b", "c", "d", "a");

        final String REF = "a";

        // Check the frequency
        int nb = Collections.frequency( list, REF );
        System.out.println( "The value "+ REF + " is " + nb + " times in the list" );
        long nbLambra =
        	.filter( a -> a.equals( REF ) )

        System.out.println( "\nUsing Lambda" );
        System.out.println( "The value "+ REF + " is " + nbLambra + " times in the list" );


The output will be:

The value a is 2 times in the list

Using Lambda
The value a is 2 times in the list

Note: The second option is more fancy, but much slower. So the first version is preferable.


Class Collections Javadoc

Share this article:

Recent Comments