# Find Count of Most Frequent Item in an Array in Java

## The challenge

Complete the function to find the count of the most frequent item of an array. You can assume that input is an array of integers. For an empty array return ``

Example

``````input array: [3, -1, -1, -1, 2, 3, -1, 3, -1, 2, 4, 9, 3]
ouptut: 5
``````

## The solution in Java code

Option 1:

``````import java.util.*;

public class Solution {
public static int mostFrequentItemCount(int[] collection) {
if (collection.length==0) return 0;
Map<Integer, Integer> m = new HashMap<>();
for (Integer i : collection)
m.merge(i, 1, Integer::sum);
return Collections.max(m.values());
}
}
``````

Option 2:

``````import java.util.stream.Stream;
import java.util.Arrays;
import java.util.stream.Collectors;
import static java.util.function.Function.identity;
import static java.util.stream.Collectors.counting;

public class Solution {
public static int mostFrequentItemCount(int[] collection) {
return (int)Arrays.stream(collection).mapToObj(i -> i)
.collect(Collectors.groupingBy(identity(), counting()))
.values().stream().mapToLong(c -> (long)c).max().orElse(0);
}
}
``````

Option 3:

``````import java.util.Collections;
import java.util.ArrayList;

public class Solution {
public static int mostFrequentItemCount(int[] collection) {
ArrayList<Integer> arr = new ArrayList<>();
for (Integer i : collection)
int most = 0;
for (Integer i: arr) {
int b = Collections.frequency(arr,i);
if (b>most)
most=b;
}
return most;
}
}
``````

## Test cases to validate our solution

``````import org.junit.Test;
import static org.junit.Assert.assertEquals;

public class FrequentExampleTests {
@Test
public void tests() {
assertEquals(2, Solution.mostFrequentItemCount(new int[] {3, -1, -1}));
assertEquals(5, Solution.mostFrequentItemCount(new int[] {3, -1, -1, -1, 2, 3, -1, 3, -1, 2, 4, 9, 3}));
}
}
``````