×

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 Call a Method in Java

In Java, a method is a collection of statements that perform a specific task or action.It can accept data with the help ofitsarguments. It  is also called a function. In order...

9 minutes read.

Sierpinski Number in Java

The Sierpinski triangle—is it a fractal? The Sierpinski Triangle fractals. A self-similar fractal is the Sierpinski triangle. It is made of an equilateral triangle with its residual area successively reduced by...

3 minutes read.

Java Create File

A File is a hypothetical way, which has no genuine presence. It is very much like while "using" that File that the major real activity of putting away something in...

5 minutes read.

Array and String with Examples in Java

Array in Java: An array in Java is a group of variables with similar types that have a common name. The arrays used in Java differ from those used in C/C++. Key...

6 minutes read.

How to download Eclipse for Java

Introduction: We write a java program, and when we want to run it, we need software to run it. Eclipse is a kind of software used to execute a JavaFX...

3 minutes read.

Java Final Keyword

In Java, the last keyword is used to limit the user. The applications of the java final keyword have large range of usage in program development. Last can be: variablemethodclass A final...

3 minutes read.

Multithreading in Java

Multithreading is a specialized form of multitasking. It is responsible for executing more than one task at a time of a single program, and each task is a separate thread. A program...

8 minutes read.

How to Convert String to Object in Java

How to Convert String to Object in Java The Object is the super class of all classes. So you can assign a string to Object directly. There are two methods to...

3 minutes read.

What’s new in Java 12

On March 19th, 2019, the Java 12th edition was released. After releasing this edition, they have decided to release every new edition every six months. This version is the advanced...

5 minutes read.

Java StringWriter Class

The StringWriter class is a character stream in which it is used to store the output consisting of characters into the string buffer. Upon collecting output into a string buffer,...

3 minutes read.

Java Integer compareUnsigned() method

The compareUnsigned() method of Integer class compares two int objects numerically by treating the values as unsigned. Syntax public static int compareUnsigned(int x , int y) Parameters The parameters ‘x’ and ‘y’ represent the...

1 minute read.

Knapsack problem in Java

We have a collection of items in the knapsack problem. Every object has a weight and a value. These things should go in a knapsack. But there is a weight...

3 minutes read.

Math fma () method in java

In java, the Math module constitutes of fma () Method in it. This method can be accessed in two ways which can be differentiated by the parameters which are given...

4 minutes read.

Web Crawler in Java

In this article, you will be acknowledged with what a web crawler in java is and what are its functions. You will also be able to understand where to implement...

4 minutes read.

Print Matrix Diagonally in Java

The aim is to print the elements of a matrix of size n*n in some kind of a diagonal pattern. Input : mat[3][3] = {{1, 2, 3},                      {4, 5, 6},                      {7,...

3 minutes read.

Split the Number String into Primes in Java

Given is a string that only contains digits and serves to represent a number. Our goal is to split the string of numbers in a way that ensures each segment...

2 minutes read.

Balanced Prime Number in Java

This section will cover the definition of a balanced prime number as well as how to find one using a Java program. Balance Prime Number A prime number that is equivalent to...

5 minutes read.

Java String Matches vs Contains

String Matches in Java The matches() function and its variations are used to determine whether or not a provided text matches a regular expression. The functioning as well as output of...

3 minutes read.

The final Keyword in Java

The final keyword is employed in several instances. Firstly, the non-access modifier final only applies to variables, methods, and classes. The final can be used in the following situations. Final Variables When...

6 minutes read.

Segment Tree in Java

Binary trees can address a variety of issues; however, the Segment Tree is more efficient in terms of time complexity. The segment tree in Java is represented using an array. Native...

4 minutes read.