×

Sort Elements by Frequency in Java

To sort the elements in Java by using frequency, we need an input array. We should create a function that sorts the elements in an array by using their frequencies in descending or ascending order. We have to print the elements that first appear in the list, and if the element is repeated two or more times, then we should follow the following order:

Input array: [17, 11, 13, 14, 17, 11, 17, 11, 14, 15, 11, 19, 13]

The output array in sorted according to the frequency in ascending order:

Output array: [11, 11, 11, 11, 17, 17, 17, 13, 13, 14, 14, 15, 19].

Each component occurs exactly once or at frequency 1. As a result, the order in which the elements appear in the input array matches the order in which they appear in the output array.

Algorithm or step-by-step sequence:

Step 1: First, create a LinkedHashMap with the name countele. The elements in the countele are keys and their frequencies are values.

Step 2: now check each element of the arr in the countele. If the element is found or present in the countele, then we have to increment the count or frequency by 1. Otherwise, we have to insert the element with 1 as its value.

Step 3: now create or construct an arraylist called entrylist which holds or responsible of holding all the entry objects of countele.

Step 4: based on values of the entry objects we have to sort the entrylist.

Here we will use a function named Collections.sort() which sort the elements in the list or array.

Step 5: at last, the entrylist consist of all the elements in the sorted order based on their frequency and we have to print them in the decreasing or increasing order as their frequencies.

Example code:

The implementation of steps above in algorithm are performed via code.

import java.util.*;
import java.util.Arrays;
import java.io.*;
import java.util.Collections;
import java.util.Comparator;
import java.util.ArrayList;
import java.util.Map;
import java.util.LinkedHashMap;
import java.util.Map.Entry;
 
public class frequencysort
{
    private static void frequencysort(int[] arr)
    {
        //Create a LinkedHashMap with the elements' occurrences as values and keys. Keep in mind that LinkedHashMap preserves element insertion order.
         Map<Integer, Integer> counteleMap = new LinkedHashMap<>();
         
        //Check the number or value existsin  countele 
         
        for (int i = 0; i < arr.length; i++) 
        {
            if (counteleMap.containsKey(arr[i]))
            {
                //if the presence of element in the countele then we have to increament by 1
                 
                counteleMap.put(arr[i], counteleMap.get(arr[i])+1);
            }
            else
            {
                //If the presence of element is not there in countele then, insert the value element  with 1 as its value.
                 
                counteleMap.put(arr[i], 1);
            }
        }
         
        // now create an arraylist which holds all the values in the countelemap with an entry of object.
         
        ArrayList<Entry<Integer, Integer>> entrylist = new ArrayList<>(counteleMap.entrySet());
         
        //Sort the entrylist based on values
         
        Collections.sort(entrylist, new Comparator<Entry<Integer, Integer>>() 
        {
            @Override
            public int compare(Entry<Integer, Integer> a, Entry<Integer, Integer> b) 
                {
                    return b.getValue().compareTo(a.getValue());
                }
            }
        );
         
        //print the sorted array list in the increasing order or desecnding order according to the frequency.
         
        System.out.println("the input array is : "+Arrays.toString(arr));
         
        System.out.println("sorted array list in the increasing order or desecnding order according to the frequency :");
         
        System.out.print("[ ");
         
        for (Entry<Integer, Integer> entry : entrylist) 
        {
            int freq = entry.getValue();
             
            while (freq >= 1)
            {
                System.out.print(entry.getKey()+" ");
                 
                freq--;
            }
        }
         
        System.out.print("]");
    }
     
    public static void main(String[] args) 
    {
        frequencysort(new int[] {17, 11, 13, 14, 17, 11, 17, 11, 14, 15, 11, 19, 13});
    }
}

Output:

cd /home/cg/root/6368984ad6872
the input array is : [17, 11, 13, 14, 17, 11, 17, 11, 14, 15, 11, 19, 13]
sorted array list in the increasing order or desecnding order according to the frequency :
[ 11 11 11 11 17 17 17 13 13 14 14 15 19 ]

Complexity analysis for the above program is calculated based on the number of occurrences and swap:

The program has an O(n * log(n)) time complexity because sorting is being used. Additionally, an array list was made to house the outcomes. Consequently, the space complexity becomes O(n), where n is the total number of elements in the input array.


Related Topics

How to Develop Programming Logic in Java?

Introduction In the world of software development, Java programming language is one of the most powerful programming languages that is used to create a wide range of applications. It includes desktop,...

18 minutes read.

Java StringReader Class

StreamReader Class technique enables character reading from a string. The java.io package contains this class. A string serves as a source in the character stream. While the Stream class is...

4 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.

Palindrome Partitioning problem in Java

In this article, you will be acknowledged about partitioning of the palindrome. It can be done in many ways. This article makes sure every method is discussed. Palindrome If a string remains...

6 minutes read.

Java Command not found

Java Command not found error is displayed if Java is not installed on the computer or if the command prompt cannot find Java.exe to run the program. Our Java software...

3 minutes read.

Figurate Number in Java

There have been several uses for figurate or figural numerals throughout history. A number that may be expressed by regular, distinct geometric shapes with spaced evenly points is referred to...

4 minutes read.

Java Sort String

In this article, you will be acknowledged about how to sort a string in Java. Introduction Firstly, let us revise what is string Strings are collections of characters that are frequently used in...

4 minutes read.

Java calculate age

In this section, we will create a Java program that calculates age from the given date of birth or current date. In order to get the date of birth from the current...

6 minutes read.

Java ArrayList

Java ArrayList Class A Java ArrayList class is a dynamic array which is used to store the elements. It is a part of collection framework. It implements the List Interface and inherits the...

12 minutes read.

Java Math sinh() Method

The sinh() method of Java Math class returns the hyperbolic sine of the specified double value. Syntax: public static double sinh(double x) Parameters: The parameter ‘a’ represents the number whose hyperbolic sine is to...

2 minutes read.

POJO in Java

Plain old Java Object, in short, is called POJO in Java. POJO is an everyday object that is not subject to any specific limitations. We can use POJO in any Java...

3 minutes read.

Java Class Name

How to write a class name? The following considerations should be made while writing class names. The name of the current class shouldn't be based on a preset or existing class. Java keywords...

3 minutes read.

Java Password Generator

Generally, we must create a strong password for security reasons. In Java, there are numerous strategies for creating secure passwords. We will learn how to create a strong password in...

4 minutes read.

Java Print Writer

PrintWriter: It is used to write output data from the file. It is the class of Java.io package. It inherits the properties of the Writer class. Writer Class: It is a class of...

4 minutes read.

Morris Traversal for Inorder in Java

Through Morris’s traversal, a tree is traversed without the aid of recursion or stacks. Based on the threaded binary tree, the Morris traversal is used. We perform internal modification throughout...

4 minutes read.

What is Core Java?

The fundamental Java, which includes the fundamental idea of the Java programming language, is referred to as "Core Java." The definition of "Core" is the core idea of something. Core...

3 minutes read.

Pangram Program in Java

If a string comprises all alphabet letters from A to Z or from a to z without regard to case, it is referred to as a pangram. Some examples of pangram...

3 minutes read.

TreeSet in Java

Java TreeSet with Example Java TreeSet implements the Navigable Set interface. It stores the objects in ascending order. It contains unique elements. Access and retrieval time is fast. It does not...

8 minutes read.

Java Trim

Leading and leaving spaces are removed by the built-in Java String trim() method. Space seems to have the Unicode element of "x0040." Java trim() function looks for all of these...

3 minutes read.

The Diamond Operator in Java 7

The Diamond operator is a comparatively recent Java operator originally developed in JDK 7 to enhance type identification and eliminate boilerplate Java code. The Diamond operator is characterized by a...

2 minutes read.