×

Find the Frequency of Each Element in the Array in Java

We may count the occurrence of each element in the array of items. Maintaining one array to store the counts of each array element is one strategy for solving this issue. The frequency of each element is calculated by iterating through the array, and it is then stored in another array called fr.

Example

Input : arr [ ] = [1,2,4,3,3,2,1]

Output:

Element    Frequency

  1. 2
  2. 2
  3. 2
  4. 1

Method 1

By using Loops

Algorithm

  • STEP 1: BEGIN
  • Initiate array[] = [1, 2, 7, 3, 2, 2, 2, 1] .
  • Create a frequency [ ] of array[] length in step three.
  • SET vis = -1 in step four.
  • for (i=0; iarr.length; i++)
    • SET count is 1.
  • for (i=0;i<frequency.length;i++) 
  • PRINT array [i] and frequenct [i] if (frequency [i]!=visited)

FrequencyOfElements.java

import java.util.*;
public class FrequencyOfElements {  
// Main section of the program where execution begins
    public static void main (String[] s) {  
        // creating object for the scanner class
        Scanner sc=new Scanner (System.in);
        System.out.println(" Enter array size ");
        // enter the size of the array
        int n=sc.nextInt();
        // array declaration 
        int array[] = new int [n];
        System.out.println(" Enter array elements ");
        // enter the array elements
        // array initialisation
        for(int i=0;i<n;i++)
        {
            array[i]=sc.nextInt();
        }
        // printing the array elements
        System.out.println(" The array elements are ");
        for(int i=0;i<n;i++)
        {
            System.out.print(array[i]+" ");
        }
        System.out.println();
        //Array frequency will store frequencies of an  element  
        int [] frequency = new int [array.length];  
        int vis = -1;  
        for(int j = 0; j < array.length; j++){  
            int count = 1;  
            // running the for loop from j+1 index to end of the array 
            for(int i = j+1; i < array.length; i++){ 
                // if 2 elements are equal then count cariable will be incremented
                if(array[i] == array[j]){  
                    count++;  
                    //To avoid counting same element again  
                    frequency[i] = vis;  
                }  
            } 
            // if the element is not visited then only count will be updated in the frequency array
            if(frequency[j] != vis)  
                frequency[j] = count;  
        }  
  
        //Displays the frequency of each element present in array  
        System.out.println(" - -- --- --- --- -----------");  
        System.out.println(" Elements | Frequency");  
        // printing the frequencies of array Elements with respect to their array elements
        for(int j = 0; j < frequency.length; j++){  
            if(frequency[j] != vis)  
                System.out.println("    " + array[j] + "    |    " + frequency[j]);  
        }  
    }}  

Output

Enter array size 
5
 Enter array elements 
1 2 1 3 3
The array elements are
1 2 1 3 3 
-----------------------
 Elements | Frequency
    1    |    2
    2    |    1
    3    |    2

Method 2

FrequencyOfElements2.java

By Using Hashing

import java.util.*;
class FrequencyOfElements2
{
static void Freqz (int arr[], int n)
{
Map<Integer, Integer> m1 = new HashMap < > () ;
// Go through the elements of an array and 
for (int i = 0; i < n; i++)
{
if (m1.containsKey(arr[i]))
{
m1.put(arr[i], m1.get(arr[i]) + 1);
}
else
{
m1.put(arr[i], 1);
}
}
// Traversing  through map and printing the  frequencies
for (Map.Entry<Integer, Integer> traversal : m1.entrySet())
{
System.out.println(traversal.getKey() + " " + traversal.getValue());
}
}
public static void main(String s[])
{
    Scanner sc = new Scanner(System.in);
    System.out.println(" Enter size of the array ");
    int n=sc.nextInt();
    int a[]=new int [n];
    System.out.println("Enter array elements");
    for(int i=0;i<n;i++)
    {
        a[i]= sc.nextInt();
    }
Freqz(a, n);
}
}

Output

Enter size of the array 
8
Enter array elements
12 12 32 44 44 10 10 67
32 1
67 1
10 2
12 2
44 2

By using HashMap

FrequencyOfElements3.java

import java.io.*;
import java.util.*;
class FrequencyOfElements3
 {
static void Freqz(int arr[], int size)
{
HashMap<Integer, Integer> h1 = new HashMap<Integer, Integer> () ;


for (int j=0;j<size;j++) {
if (h1.containsKey(arr[j])) {


h1.put(arr[j], h1.get(arr[j]) + 1);
}
else {


h1.put(arr[j], 1);
}
}
// Printing the freqMap
for (Map.Entry e : h1.entrySet()) {
System.out.println(e.getKey() + " " + e.getValue());
}
}


// Driver Code
public static void main(String s[])
{
    Scanner sc = new Scanner(System.in);
    System.out.println(" Enter size of the array ");
    int n=sc.nextInt();
    int a[]=new int [n];
    System.out.println("Enter array elements");
    for(int i=0;i<n;i++)
    {
        a[i]= sc.nextInt();
    }

Freqz(a, n);
}
}

Output:

Enter size of the array 
5
Enter array elements
10 20 10 30 20
20 2
10 2
30 1

Related Topics

HashMap Vs HashTable

HashMap HashMap is the basic implementation of the map interface in Java. HashMap stores the data in key and value pairs. Keys are used to access the value of the element. It...

5 minutes read.

House Numbers in Java

In this section, we will discuss about house number in Java. It is a sum of cubes, each of which has a dimension of h + 1. There is a...

3 minutes read.

Rectangular Numbers in Java

In this tutorial, we will understand the meaning of a rectangular number in Java with the aid of examples, illustrations, and implementations. It is one of the popular coding interview...

3 minutes read.

How to Convert long to int in Java

How to Convert long to int in Java When we assign a larger type value to a variable of smaller type, then we need to perform explicit casting for the conversion....

2 minutes read.

Java LinkedList vs ArrayList

LinkedList In LinkedList, each element is a distinct entity containing an information portion and an address component, and the elements are not kept in consecutive locations. Pointers & addresses are used...

3 minutes read.

Application of Array in Java

In this article we are going to acknowledge about what the array is, types of arrays and their applications. What is an array? An array is often a set of interrelated elements...

4 minutes read.

Inheritance Program in Java

Inheritance Program in Java Inheritance is one of the important pillars of Object-Oriented Programming that facilitates parent-child relationships in programming. Using inheritance, we can create a new class with the help...

7 minutes read.

How to Print array in Java?

A Java array is a data structure that allows us to hold components of the same data type. An array's items are kept in a single memory region. As a...

6 minutes read.

Collection Interfaces in Java with Examples

In this tutorial, we will discuss collection interfaces in Java with Examples. Introduction The Collection Interface is an individual from the Java Collections Framework. It is a root point of interaction of...

4 minutes read.

How to Create a Package in Java?

For the most part, how to create a package in Java generally, a package is defined as a collection of relevant or irrelevant items together in a very major way....

7 minutes read.

Java Program to remove duplicate characters in a string

In strings, we can find many characters present one or more times in a string; accessing a particular character is difficult due to repetition. Duplicate characters will present in the...

5 minutes read.

Generic Linked List in Java

A linear data structure known as a Linked List stores values in nodes. As we already know, each node has two properties: its value and a link to the node...

6 minutes read.

How to run Java Program in Command Prompt

How to run Java Program in Command Prompt In this section, we will learn how to write, save, compile, and execute or run a Java program in the Command Prompt. Note: One...

3 minutes read.

What is anagram in Java?

In this section will explain what an anagram is in Java and demonstrate how to determine whether or not a text is an anagram. In Java interviews, the anagram Java...

4 minutes read.

String Coding Interview Questions in Java

What is String in Java?In Java, a String is a Class that is defined in the java.lang package. It isn't a basic data type like int or long. Character Strings...

5 minutes read.

Block Swap Algorithm for array rotation in Java

An array and r, the rotation factor by which the array must be rotated, are both provided to us. We must then return the rotated array. A well-known and popular method is...

4 minutes read.

Java gc()

Garbage collection Java language provides different ways to perform the task of memory management. In Java, objects are declared and assigned references. Once lifeof an object is completed it is dereferenced...

4 minutes read.

Exception Handling Program in Java

Exception Handling Program in Java Exception means something that is abnormal. In Java, an exception is treated as a problem that disrupts the normal flow of the program. An exception leads...

7 minutes read.

Java Integer toUnsignedLong() method

The toUnsignedLong() method of Java Integer class returns a long value by simply converting the given argument to long after an unsigned conversion. Syntax public static long toUnsignedLong (int  x) Parameters The parameter ‘x’...

1 minute read.

Java Strictfp Keyword

Strictfp is used to impose limits on floating-point calculation. It ensures that we will get the same result on every platform while performing an operation with the floating-point variable. The floating-point calculation is platform-dependent due...

1 minute read.