Find Count of Most Frequent Item in an Array in Java

1 min read 219 words

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)
            arr.add(i);
        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}));
  }
}
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags

Recent Posts