Count Frequency of Each Element in Array in java

               Array has similar elements. If you want to find the frequency of occurrence in each number, let us implement some java programs.

There are two types to implement this concept.

  1. 1.      Using Array
  2. 2.      Using Streams

1.      Using Array:

This method uses array to find the Number of occurrences. The steps are given below..

  • It uses a public class with two functions.
  • ‘countit()’
  • It gets the array and maximum value as input.
  • A for loop is used to find the number of occurrences.
  • Using maximum value, each element is checked and the occurrence is printed.
  • ‘main()’
  • It reads the input from the user.
  • Call the ‘countit()’ function to get the output.

Program:

public class FrequencyArrayEg {

    public static void countIt(int[] arr, int m_Value) {

        int[] freq = new int[m_Value + 1];

        // Count the number of occurrences

        for (int no : arr) {

            freq[no]++;

        }

        // Print frequencies of the occurrences

        System.out.println("The Element Frequencies:");

        for (int i = 0; i <= m_Value; i++) {

            if (freq[i] > 0) {

                System.out.println(i + " -> " + freq[i]);

            }

        }

    }

    public static void main(String[] args) {

        int[] a = {31, 11, 22, 31, 4,11, 32,45};

        countIt(a, 45);

    }

}

Output:

C:\raji\blog>javac FrequencyArrayEg.java

C:\raji\blog>java FrequencyArrayEg

The Element Frequencies:

4 -> 1

11 -> 2

22 -> 1

31 -> 2

32 -> 1

45 -> 1

2.Using Streams:

              This program uses streams to find the frequency of occurences.

  • It includes the built in packages.
  • A public class with main() is developed.
  • An integer array is created with values.
  • A long int variable is declared from Map. using built in functions, the frequency of occurrences is found and printed.

Program:

import java.util.Arrays;

import java.util.Map;

import java.util.stream.Collectors;

public class FrequencyStreamsEg {

    public static void main(String[] args) {

        int[] a = {41, 22, 13, 41, 22, 2, 13, 53, 16, 41};

        Map<Integer, Long> fMap = Arrays.stream(a)

            .boxed()

            .collect(Collectors.groupingBy(num -> num, Collectors.counting()));

        System.out.println("The Element Frequencies: " + fMap);

    }

}

Output:

C:\raji\blog>javac FrequencyStreamsEg.java

C:\raji\blog>java FrequencyStreamsEg

The Element Frequencies: {16=1, 2=1, 53=1, 22=2, 41=3, 13=2}

Yes. That’s the way to count the frequency of each element in array was developed in java. Keep Coding!!!

Comments

Popular posts from this blog

How to create a XML DTD for displaying student details

How to write your first XML program?

Java NIO examples to illustrate channels and buffers.