1

I'm trying to figure out how to get the frequency of items within a list. When I approach this problem I typically, in the past, did:

int occurrences = Collections.frequency(list, 0);

It works when my list is a List<Integer> list. Is there a way to do this if I'm using int[] list? When I try collections, my list gets converted and then my code breaks. I can convert my code if needed, but was wondering, if there was a way to get the frequency from int[] instead.

user unknown
  • 35,537
  • 11
  • 75
  • 121
Lostsoul
  • 25,013
  • 48
  • 144
  • 239
  • 2
    by writing your own function :) It's one `for-loop`... – K Mehta Apr 12 '12 at 04:39
  • @userunknown sorry, I was composing the question while testing it and got my thoughts mixed up. I think I fixed it, sorry about that. Might be a sign thats its time to go to bed. – Lostsoul Apr 12 '12 at 04:49

4 Answers4

2

You can (1) write your own linear-time frequency method, or (2) convert to an array of boxed int types and use Arrays.asList with Collections.frequency.

int[] arr = {1, 2, 3};
Integer[] boxedArr = new Integer[arr.length];
for(int i = 0; i < arr.length; i++)
    boxedArr[i] = arr[i];
System.out.println(Collections.frequency(Arrays.asList(boxedArr), 1));
blackcompe
  • 3,180
  • 16
  • 27
  • I'm guessing from the [new question](http://stackoverflow.com/q/10133584/422353) that this did not worked in the end because is an array of primitive `int`'s. – madth3 Apr 13 '12 at 00:33
2

You could create a List from the int[], but otherwise, you just have to write your own.

int[] l = //your data;
List<Integer> list = new List<Integer>();
for(int i : l)
  list.add(i);

int o = Collections.frequency(list, 0);

Or Arrays.asList(l); to make it shorter.

Jon Egeland
  • 12,470
  • 8
  • 47
  • 62
2
int occurrences = Collections.frequency(Arrays.asList(list), 0);

Or if you are against converting it to a list:

int occurrences = 0;
for (int i = 0; i < list.length; i++)
{
    if(list[i] == X) // X being your number to check
        occurrences++;
}
Greg Case
  • 3,200
  • 1
  • 19
  • 17
Jeames Bone
  • 564
  • 4
  • 12
  • The use of `asList` will not work because is an array of primitives and not objects, but the counting is the the way I'd use since it does not require building new objects. – madth3 Apr 13 '12 at 00:38
1

You can do this way as well.

List<Integer> intList = Arrays.asList(new Integer [] {
      2, 3, 4, 5, 6,
      2, 3, 4, 5,
      2, 3, 4,
      2, 3,
      2
    });

  System.out.println(" count " + Collections.frequency(intList, 6));
UVM
  • 9,776
  • 6
  • 41
  • 66