Home » Java » Why is Collections.frequency not working as expected on converted list?

Why is Collections.frequency not working as expected on converted list?

Posted by: admin December 28, 2021 Leave a comment

Questions:

I have used Collections.frequency in the past and its worked fine but I’m having problems now that I’m using an int[].

Basically Collections.frequency requires a array but my data is in the form of a int[] so I convert my list but am not getting an results. I think my mistake is in the converting of the list but not sure how to do it.

Here’s an example of my problem:

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;

public class stackexample {
    public static void main(String[] args) {
        int[] data = new int[] { 5,0, 0, 1};
        int occurrences = Collections.frequency(Arrays.asList(data), 0);
        System.out.println("occurrences of zero is " + occurrences); //shows 0 but answer should be 2
    }
}

I don’t get an error just zero but I get weird data when I try to list the items in Arrays.asList(data), if I just add data directly, it wants to convert my list into collections<?>

Any suggestions?

Answers:

This works:

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

public class stackexample {
    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); //shows 0 but answer should be 2
    }
}

It’s because Arrays.asList isn’t giving you what you think it is:

http://mlangc.wordpress.com/2010/05/01/be-carefull-when-converting-java-arrays-to-lists/

You’re getting back a List of int [], not int.

###

You problem is from this instruction Arrays.asList(data).

the return of this method is List<int[]> not List<Integer>.

here a correct implementation

    int[] data = new int[] { 5,0, 0, 1};
    List<Integer> intList = new ArrayList<Integer>();
    for (int index = 0; index < data.length; index++)
    {
        intList.add(data[index]);
    }

    int occurrences = Collections.frequency(intList, 0);
    System.out.println("occurrences of zero is " + occurrences);

###

The API expects an Object, and primitive types are not objects. Try this:

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;

public class stackexample {
    public static void main(String[] args) {
        Integer[] data = new Integer[] { 5,0, 0, 1};
        int occurrences = Collections.frequency(Arrays.asList(data), Integer.valueOf(5));
        System.out.println("occurrences of five is " + occurrences); 
    }
}