×

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

Java Database Connectivity with MySQL

In this tutorial, we will learn how to connect Database with MySQL in Java. 5 Steps to Connect to the Database in Java Load the driver (or) Register the driver classEstablish a...

4 minutes read.

How to Solve the Deprecated Error in Java?

Deprecated Java methods should not be used because they are deprecated (often, there are better, more modern alternatives). API update. Until now, Java has kept everything backward compatible and never...

3 minutes read.

Java Math ulp() Method

The ulp() method of Java Math class returns the size of an ulp of the argument. Syntax: public static double ulp(double x)public static float ulp(float x) Parameters: The parameter ‘x’ represents the floating-point number...

2 minutes read.

How to override toString() method in Java?

Java is an object-oriented language. It only works with classes and objects. Thus, whenever we need to calculate, we need an object or objects that belong to the class. The Java method...

2 minutes read.

Reverse a String in Java

Reversing a string means that if we have a string called “what is your name”, the reversed format is “eman ruoy si tahw”. Reversing a string involves totally flipping the...

3 minutes read.

Blockchain in Java

Blockchain is a continuously expanding ledger that maintains an immutable, secure, and chronological record of all transactions that have ever occurred. It can be utilized to securely transfer money, assets,...

9 minutes read.

Stack Program in Java

Stack Program in Java The Stack class is part of the collection framework that inherits the Vector class. Thus, the Stack class can also be called a subclass of the Vector...

5 minutes read.

How to increment and decrement date using Java?

Before understanding how to increment and decrement the date, one must know about the Calendar class in Java. The Java calendar class offers methods for converting dates between a given moment...

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.

Find next greater number with same set of digits in Java

It contains a number (num). Finding the smallest number that has the same number of elements as num that is also larger than num is the task at hand. If...

8 minutes read.

Java Lock

A lock is indeed a threaded synchronization technique similar to Java's synchronized blocks, however, locking can be more complex. It's not like we can completely get rid of the synchronized...

5 minutes read.

Constructor Program in Java

Constructor Program in Java In Java, a constructor is a piece of code that is used to create an object. A constructor is called implicitly when an object is created in...

7 minutes read.

Bully Algorithm code in Java

Election algorithms include the bully algorithm, mainly used to select a coordinate. To find a coordinator in a distributed system that can carry out the tasks required by other processes,...

4 minutes read.

Difference Between Data Hiding and Abstraction in Java

Abstraction: Data Abstraction and Data Hiding ideas are utilised to show the expected data to the end client and conceal the superfluous subtleties, however, for specific purposes like decreasing the framework's...

10 minutes read.

Java Math getExponent() Method

The getExponent() method of Math class returns the unbiased exponent of the argument. Syntax: public static int getExponent (double d) Parameters: The parameter ‘d’ represents the double value. Return Value: The getExponent () method returns the...

1 minute read.

String Programs in Java

String Programs in Java: In Java, a String is an immutable object that represents a sequence of characters. For example, “Tutorial” is a string that consists of 8 characters: ‘T’,...

10 minutes read.

Libraries in Java

The Java Class Library (JCL) specifically is a set of dynamically loadable libraries that Java Virtual Machine (JVM) languages can call at any run time, which is fairly significant because...

6 minutes read.

Null Pointer Exception in Java

It is a runtime error exception. The null value is allocated to the object reference in this exception. We will explicitly throw this null pointer exception when the program wants...

3 minutes read.

How to Install Java on MAC

There are many possible ways to install java on mac. This article is based on the installation of java on mac. The operating system platform is Mac OS X, macOS and...

3 minutes read.

Zebra Puzzle Problem in Java

Complex puzzles like the zebra puzzle demand a lot of work and mental training to complete. Because it was created by renowned German scientist Albert Einstein, it is also sometimes...

10 minutes read.