HashMap examples: To check a product is available in the list or not.

              Let us create this program using hashMap.  A list of products with its prices are added to the hashMap.

Steps:

  • ·       Import the built-in packages java.util.HashMap,java.util.Map.
  • ·       A public class is developed with main() function.
  • ·       Constructor: initializes the object.
  • ·       addItems() : it inserts the product and price.
  • ·       getPrice() : This function gets the price for the product.
  • ·       updatePrice(): it updates the price.
  • ·       printPrice() : This function prints the product and price.

Program:

// import the built-in packages

import java.util.HashMap;

import java.util.Map;

//Create a public class

public class ProductPricesPrint {

    private Map<String, Double> prices;

//constructor of the class to initialise the object.

    public ProductPricesPrint() {

        prices = new HashMap<>();

    }

//Member function addItem()

    public void addItem(String Product, double price) {

        prices.put(Product, price);

    }

//Member function getPrice()

    public Double getPrice(String Product) {

        return prices.get(Product);

    }

//updatePrice() function to update the value.

    public void updatePrice(String Product, double newPrice) {

        if (prices.containsKey(Product)) {

            prices.put(Product, newPrice);

        }

    }

//To print the product list

    public void printPrice(String Product) {

        Double price = prices.get(Product);

        if (price != null) {

            System.out.println("The price of " + Product + " is: " + price);

        } else {

            System.out.println(Product + " is not available.");

        }

    }

//Main() function definition

    public static void main(String[] args) {

        ProductPricesPrint productPricesPrint = new ProductPricesPrint();

    

        productPricesPrint.addItem("Cricket bat", 1500);

        productPricesPrint.addItem("Cricket ball",200);

        productPricesPrint.addItem("Hockey Bat",1000);

        productPricesPrint.addItem("Hockey Ball",240);

        productPricesPrint.addItem("FootBall",500);

        productPricesPrint.addItem("BasketBall",450);

      //To check the product in the HashMap

        productPricesPrint.printPrice("BasketBall");

        productPricesPrint.printPrice("carrom");

    }

}

Output:

C:\raji\blog>javac ProductPricesPrint.java

C:\raji\blog>java ProductPricesPrint.java

The price of BasketBall is: 450.0

carrom is not available.

This is the way of checking a product list is available in the list or not. Keep coding!!!

TreeMap implementation in java

              A TreeMap is a category in Map interface. To implement this in java, an interface “NavigableMap” is used. It also stores the key, value pair in a natural order or any specified order.

TreeMap has some specific features are listed below….

  • ·       It accept only null values,not the null keys.
  • ·       The ordering of entries may be in natural order or any order provided by the comparator.
  • ·       It follows Red-Black Tree for internal implementation.

How to implement TreeMap in java?

  • It includes builtin packages in java(java.util.Map,java.util.TreeMap).
  • A public class TreeMapEg is created with main function().
  • An object instance is created for TreeMap.
  • To add the key, value pair, a builtin function put() is used.
  • Get() function is used to find the given key in the treeMap and gives you the key value pair.
  • containsKey() checks the key in the treeMap.
  • getValue(),getKey() is used to get the value and key.
  • Remove() is used to delete the key,value.
  • Clear () clears all the values in treeMap.
  • isEmpty() returns a Boolean value.

Program:

import java.util.Map;

import java.util.TreeMap;

public class TreeMapEg {

    public static void main(String[] args) {

        // Let us create a TreeMap

        Map<String, Integer> treeMap1 = new TreeMap<>();

        // inserting  values for key-value pairs

        treeMap1.put("Onion", 500);

        treeMap1.put("Carrot", 200);

        treeMap1.put("Brinjal", 300);

        treeMap1.put("Tomato", 400);

        treeMap1.put("Potato",350);

        treeMap1.put("Cabbage",500);

        // Search and retrieve a key,value pair

        System.out.println("Weight of the Tomato: " + treeMap1.get("Tomato"));

        // Check for a key

        if (treeMap1.containsKey("Brinjal")) {

            System.out.println("Brinjal is available.");

        }

         System.out.println("The list of vegetables and its price:");

        //Loop to print the value,key pair

        for (Map.Entry<String, Integer> entry : treeMap1.entrySet()) {

            System.out.println(entry.getKey() + ": " + entry.getValue());

        }

         // Remove a pair

        treeMap1.remove("Cabbage");

         // Here, the size of TreeMap is displayed

        System.out.println("Size of the TreeMap: " + treeMap1.size());

         // Clear the contents in the TreeMap

        treeMap1.clear();

         //Check the treeMap emptiness

        if(treeMap1.isEmpty())

        System.out.println("The TreeMap is empty");

    }

}

Output:

C:\raji\blog>javac TreeMapEg.java

C:\raji\blog>java TreeMapEg

Weight of the Tomato: 400

Brinjal is available.

The list of vegetables and its price:

Brinjal: 300

Cabbage: 500

Carrot: 200

Onion: 500

Potato: 350

Tomato: 400

Size of the TreeMap: 5

The TreeMap is empty

This is the simple way of implementing TreeMap in java. If you have  any queries, post in the comment.Keep coding!!!!

LinkedHashMap implementation in java

               It is a type of map which extends ‘Map’ from java collections Framework. Here, a doubly linked list is used. This uses either insertion-order or access order to iterate the linked list.

Features:

  • ·       The iteration follows either insertion order or access order.
  • ·       The performance is balanced among the prediction of iterations and operations.
  • ·       It allows one null key and multiple null values.

Implementation of LinkedHashMap in java:

              This program creates some data structures with number of elements for mapping.

Steps:

  • ·       First, import the built in packages java.util.LinkedHashMap and java.util.Map.
  • ·       Create a public class with main() function.
  • ·       An object instance is created for LinkedHashMap.
  • ·       Using the object, the key,value pair is added to the linkedHashMap.
  • ·       Function get() is used to retrieve and display the key,value pair.
  • ·       ContainsKey() member function finds a key,value pair is available in the map.
  • ·       getKey(),getValue() retrive the key,value from the map.
  • ·       To delete a key,value pair, remove() function is used.
  • ·       Clear() function clears the entire elements.
  • ·       isEmpty() returns true when the map is empty.

Program:

import java.util.LinkedHashMap;

import java.util.Map;

public class LinkedHashMapEg {

    public static void main(String[] args) {

        // Create an object for LinkedHashMap

        Map<String, Integer> linkedHashMap1 = new LinkedHashMap<>();

        // insert the key-value pairs to the linkedHashMap

        linkedHashMap1.put("LinkedList", 50);

        linkedHashMap1.put("Stack", 20);

        linkedHashMap1.put("Queue", 30);

        linkedHashMap1.put("Tree", 40);

        linkedHashMap1.put("Binary Tree",45);

        // Extract a data

        System.out.println("Number of elements in Queue: " + linkedHashMap1.get("Queue"));

        // Check a key's availability

        if (linkedHashMap1.containsKey("Tree")) {

            System.out.println("Tree is available.");

        }

        // Create a loop to display the key,value in LinkedHashMap

        for (Map.Entry<String, Integer> entry : linkedHashMap1.entrySet()) {

            System.out.println(entry.getKey() + ": " + entry.getValue());

        }

         // Delete a key-value pair

        linkedHashMap1.remove("Binary Tree");

        // Print the size of the LinkedHashMap

        System.out.println("Size of the LinkedHashMap: " + linkedHashMap1.size());

        // Clear all the key,value pair in the LinkedHashMap

        linkedHashMap1.clear();

        // Check the linkedHashMap is empty or not

        if(linkedHashMap1.isEmpty())

        System.out.println("LinkedHashMap is empty");

    }

}

Output:

C:\raji\blog>javac LinkedHashMapEg.java

C:\raji\blog>java LinkedHashMapEg

Number of elements in Queue: 30

Tree is available.

LinkedList: 50

Stack: 20

Queue: 30

Tree: 40

Binary Tree: 45

Size of the LinkedHashMap: 4

LinkedHashMap is empty

This is the simple way of implementing LinkedHashMap program in java. Hope, this post will be useful for you. Keep coding!!!

HashMap implementation of java

             Map is an interface which stores key and value. It has various types of implementations. One of those implementations is “HashMap”.

HashMap implementation includes the following built-in functions listed below.

put(): adding key, value to the HashMap.

get(): This function gets the key and value.

containsKey(): This function checks a value is available or not.

getKey(): It gets the key.

getValue() :It retrieves the value associated with the key.

remove() :This function deletes the entry.

size() :This gives you the size of the HashMap.

clear() :It clear all the keys and values.

isEmpty(): This returns Boolean value to check the HashMap is empty or not.

Program:

import java.util.HashMap;

import java.util.Map;

public class HashMapEg {

    public static void main(String[] args) {

        // Let us create a HashMap

        Map<String, String> map1 = new HashMap<>();

        //Insert the values to the HashMap as key and value.

        map1.put("Car", "Vehicle");

        map1.put("Cricket", "Sports");

        map1.put("Shirt", "Dress");

        map1.put("Juice","Drink");

        map1.put("Orange","Fruit");

        // retrieve a value by searching by key value

        System.out.println("Car is a " + map1.get("Car"));

        // checking for an entry

        if (map1.containsKey("Cricket")) {

            System.out.println("Cricket is present in the map.");

        }

        // Loop to print the keys and values in the HashMap

        for (Map.Entry<String, String> entry : map1.entrySet()) {

            System.out.println(entry.getKey() + " is a " + entry.getValue());

        }

        // delete a key and value

        map1.remove("Fruit");

       // print the size of hashmap

        System.out.println("Size of the map: " + map1.size());

        // Clearing all the key,value pair

        map1.clear();

        //Check for map is empty or not

        if(map1.isEmpty())

        System.out.println("The map is empty" + map1.isEmpty());

    }

}

Output:

C:\raji\blog>javac HashMapEg.java

C:\raji\blog>java HashMapEg

Car is a Vehicle

Cricket is present in the map.

Cricket is a Sports

Shirt is a Dress

Car is a Vehicle

Juice is a Drink

Orange is a Fruit

Size of the map: 5

The map is empty

This is the simple implementation of HashMap using java programming. Hope this will be useful for you. Keep coding!!!

Basic operations of "Map" interface in java

     ‘Map’ is an interface in java Collections Framework. It contains a pair of values which is a key associated with its value. Map has unique values for each key. One single entry is for one value.

Features of Map:

Map has unique features compared to other data structures like queue or Stack. The features are listed below.

  • Key and Values are paired.
  • It always include the key as unique. It does not have any duplicate keys. Sometimes, it allows duplicate value.
  • Null values are also acceptable. But a single null key is accepted due to implementation purpose.

Various ways of implementing “Map”:

              “Map” can be implemented as three ways.

  • 1.       HashMap: It may be in any order. I/O operations are in constant time performance.
  • 2.       LinkedHashMap: The insertion maintains an order.
  • 3.       TreeMap: It follows a sorted order based on the program. It uses “NavigableMap” interface.

Built in methods in Map interface:

It has the following list of methods.

1. entrySet():

          It gives you the mappings of the map interface.

          Eg:  Set<Map.Entry<String, String>> entries = map.entrySet();

2.keySet():

        This function lists out the keys in the map interface.

        Eg:  Set<String> key_map =map.keySet();

3.values():

       The values of each key is displayed.

       Eg: Collection<String> value_map = map.values();

4.get(Object key)

       It is the input statement to get the key value.

       Eg: String value_map = map.get("key1");

5. put(K key_map, V value_map):

      This function creates the association for key and value in the map.

      Eg: map.put("key12", "value12");

6. remove(Object key):

      This function deletes the key.

      Eg: remove(“key12”);

7. containsKey(Object key_map):

       It checks the key is available is not by returning true or false value.

       Eg: Boolean iscontain=map.ContainsKey(“key12”);

8.containsValue(Object value_map):

             This function checks the value associated for map is available or not.

 Eg:    boolean iscontains = map.containsValue("value12");

9.size():

       It returns the number of elements in the map. Here, the elements are the “key and value”.

       Eg int the_size = map.size();

10.isEmpty():

    This function gives you `true` if the map contains has no pair of key and value.

    Eg: Boolean isEmpty_or_not = map.isEmpty();

11.clear():

    This function deletes the entire mapping in the map interface.

    Eg: map.clear();

These are the basics of map interface and its built-in member functions in java is illustrated.

TreeSet : Ceiling in right side for every element in an array

              TreeSet is an example of Set Interface. Generally, it stores the elements in ascending order. It takes the elements with non-null value. It allows the multithreading.

Ceiling on the right-side Problem:

 It is a problem which checks the each element and the smallest element should be in right side.

Implementation:

Built in class: “TreeSet”

Functions:

  •  finditCeilingOnRight(): This function is used to traverse the array from the right to left side.
  •  Ceiling() : it checks the smallest with with current element.
  • Add() :It inserts the element to the set.

Note :To update the ceiling value for result array ceil variable is used.

Steps to implement the program:

  • Include the built in package java.util.*;
  • Create a class “CeilingONRightsolution” with main() function.
  • Get the input array elements.
  • Call the function “finditCeilingOnRight()” with input array and assign it to output array.
  • finditCeilingOnRight() – It finds the length of array. check the each and every element.
  • Based on the comparison, it assign the smallest value in right or -1.
  • Add the values to output set.
  • Finally, the output is printed.

Program:

import java.util.*;

public class CeilingONRightsolution {

    public static void main(String[] args) {

        int[] arr1 = {12, 18, 40, 5, 35, 87,23};

        int[] output = finditCeilingOnRight(arr1);

        System.out.println("The input array is: " + Arrays.toString(arr1));

        System.out.println("The array after Ceiling on the right: " + Arrays.toString(output));

    }

     public static int[] finditCeilingOnRight(int[] arr1) {

        int len = arr1.length;

        int[] output = new int[len];

        TreeSet<Integer> set1 = new TreeSet<>();

        // iterating the array from right to left

        for (int i = len - 1; i >= 0; i--) {

            Integer ceil = set1.ceiling(arr1[i]);

            output[i] = (ceil != null) ? ceil : -1;

            set1.add(arr1[i]);

        }

                return output;

    }

}

Output:

C:\raji\blog>javac CeilingONRightsolution.java

C:\raji\blog>java CeilingONRightsolution

The input array is: [12, 18, 40, 5, 35, 87, 23]

The array after Ceiling on the right: [18, 23, 87, 23, 87, -1, -1]

This is the simple way of implementing this solution. Keep coding!!!

LinkedHashSet implementation in java

              HashSet+LinkedList = LinkedHashSet. A special feature of this structure is maintaining the data like a HashSet and adding a data like a linked list.

Java has the built-in package for this data structure. Let us implement it as follows.

Steps:

  • Import the built in header files LinkedHashSet and Set.
  • Include a main function with a public class. An object is created for LinkedHashSet as lHashSet1.
  • Using add() function, data elements are added.
  • Function contains() checks the particular data element is available or not and returns value according that.
  • Remove() deletes a particular element.
  • For loop is used to iterate the LinkedHashset.
  • Size() gives you the number of data elements in the LinkedHashSet.
  • To clear the data in the LinkedHashSet, use the clear() function.
  • isEmpty() checks your LinkedHashSet is empty or not.

Program:

import java.util.LinkedHashSet;

import java.util.Set;

public class LinkedHashSetEg1 {

    public static void main(String[] args) {

        // Create a HashSet as linked list

        Set<String> lHashSet1 = new LinkedHashSet<>();

        // insert the elements to the LinkedHashSet

        lHashSet1.add("Rose");

        lHashSet1.add("Lotus");

        lHashSet1.add("Jasmine");

        lHashSet1.add("Sun flower");

        lHashSet1.add("Marigold");

        // Display the hashset

        System.out.println("The elements in the LinkedHashSet: " + lHashSet1);

        // Search an element

        boolean CFlag = lHashSet1.contains("Jasmine");

        if (CFlag)

        System.out.println("The jasmine flower is available in the Hash Set");

        // Delete an element from the Linked HashSet

        lHashSet1.remove("Marigold");

        System.out.println("LinkedHashSet after removing Marigold: " + lHashSet1);

        // Iteration

        System.out.println("Iteration:");

        for (String flower : lHashSet1) {

            System.out.println(flower);

        }

        // Print the size of the LinkedHashSet

        int sizelh = lHashSet1.size();

        System.out.println("The size of the LinkedHashSet is:" + sizelh);

        // Clear the Hash Set

        lHashSet1.clear();

        if (lHashSet1.isEmpty())

        System.out.println("The Linked HashSet is Empty now");

    }

}

Output:

C:\raji\blog>javac LinkedHashSetEg1.java

 

C:\raji\blog>java LinkedHashSetEg1

The elements in the LinkedHashSet: [Rose, Lotus, Jasmine, Sun flower, Marigold]

The jasmine flower is available in the Hash Set

LinkedHashSet after removing Marigold: [Rose, Lotus, Jasmine, Sun flower]

Iteration:

Rose

Lotus

Jasmine

Sun flower

The size of the LinkedHashSet is:4

The Linked HashSet is Empty nows

That’s all. The implementation of LinkedHashSet in java is implemented successfully. It is useful when you want unique data elements.

"HashSet and its operations" - A java implementation

 What is a HashSet?

            A HashSet is a collection of elements that uses a hash table for the storage. It is a built in class in java collections Framework.

Features of HashSet:

  • ·       No specific order of storing the elements.
  • ·       The user can store a null element.
  • ·       Duplicate elements can be ignored automatically.

Let us create a HashSet with its operations in  java.

Steps to follow:

  • Using the built in class HashSet and create an object instance hSet.
  • Add(): It inserts the elements to the HashSet.
  • Contains():  It returns a Boolean value. If it is true, then the element is available in the set. Otherwise, it is not available in the HashSet.
  • Remove(): Deletes an element.
  • Iteration: use a for loop.
  • hSet.size(); This function returns the size of the HashSet.
  • clear(): The emtire Hashset is cleared using this function.
  • isEmpty(): it returns true when the Hashset is empty.

Program:

import java.util.HashSet;

public class HashSetEg1 {

    public static void main(String[] args) {

        HashSet<String> hSet = new HashSet<>();

        // Insert the elements to the HashSet by add() function

        hSet.add("Onion");

        hSet.add("Tomato");

        hSet.add("Potato");

        hSet.add("Carrot");

        hSet.add("Beans");

        hSet.add("Onion"); // it is a duplicate entry. but it is automatically ignored

        // To display the HashSet

        System.out.println("HashSet: " + hSet);

        // Search an element

        boolean containsIt = hSet.contains("Tomato");

        if(containsIt)

         System.out.println("Yes. The Hash set contains the Tomato");

        else

           System.out.println("Yes. The Hash set does not contain the Tomato");

      // Delete an element from the HashSet

        hSet.remove("Potato");

        System.out.println("HashSet after deleting Potato: " + hSet);

   // Looping and printing

        System.out.println("Print the HashSet:");

        for (String veggie : hSet) {

            System.out.println(veggie);

        }

        // let us find the size of Hash Set

        int size1 = hSet.size();

        System.out.println("The size of Hash Set is: " + size1);

        // Clear it all

        hSet.clear();

        if(hSet.isEmpty())

        System.out.println("HashSet is empty after clearing");

    }

}

Output:

C:\raji\blog>javac HashSetEg1.java

C:\raji\blog>java HashSetEg1

HashSet: [Potato, Carrot, Beans, Onion, Tomato]

Yes. The Hash set contains the Tomato

HashSet after deleting Potato: [Carrot, Beans, Onion, Tomato]

Print the HashSet:

Carrot

Beans

Onion

Tomato

The size of Hash Set is: 4

HashSet is empty after clearing

This is the way of creating a powerful HashSet and its operations in java. Keep coding!!!!

How to implement set interface in java?

            Set is a collection of elements which does not allow duplicate data. It may be finite or non-finite data. Java collections frameworks include Set interface.

How to implement set interface in java?

            Set interface can be implemented by three ways.

  1. ·       HashSet
  2. ·       LinkedHashSet
  3. ·       TreeSet

1.HashSet:

            This set uses “Hash Table” for storing the data. It follows a constant time performance.

Steps to implement:

  • ·       Include the built in packages java.util.HashSet and java.util.Set.
  • ·       Implement a class with main() function.
  • ·       An object instance is created for HashSet.
  • ·       Insert the data for the set. Here, we add vehicle names to the hash set.
  • ·       Add a duplicate data. But the data is not included in the Set displayed.

Program:

   import java.util.HashSet;

   import java.util.Set;

   public class HashSetEg {

       public static void main(String[] args) {

           Set<String> hashSet1 = new HashSet<>();

           hashSet1.add("Car");

           hashSet1.add("Truck");

           hashSet1.add("Bus");

           hashSet1.add("Van");

           hashSet1.add("Car"); // let us include a duplicate data.

           System.out.println(hashSet1);

       }

   }

Output:

C:\raji\blog>javac HashSetEg.java

C:\raji\blog>java HashSetEg

[Bus, Van, Car, Truck]

Note: you can insert more data also.

2.LinkedHashSet:

            LinkedHashSet follows a linked list for implementation.

Java implementation of LinkedHashSet is given below.

  • ·       Import the built in packages java.util.LinkedHashSet and java.util.Set.
  • ·       A public class with main() function is created.
  • ·       LinkedHashSet object is created.
  • ·       Insert the data using “add” function.
  • ·       Display the data using System.out.println(). If any duplicate is added to the set,it is not accepted.

Program:

   import java.util.LinkedHashSet;

   import java.util.Set;

   public class LinkedHashSetEg {

   public static void main(String[] args) {

           Set<String> linkedHashSet1 = new LinkedHashSet<>();

           linkedHashSet1.add("Coffee");

           linkedHashSet1.add("Tea");

           linkedHashSet1.add("Juice");

           linkedHashSet1.add("Milk");

           linkedHashSet1.add("Coffee"); // Add a duplicate data. it doesnot display in output.

           System.out.println(linkedHashSet1);

       }

   }

Output:

C:\raji\blog>javac LinkedHashSetEg.java

C:\raji\blog>java LinkedHashSetEg

[Coffee, Tea, Juice, Milk]

 3.TreeSet

            TreeSet follows a tree structure to implement this Set Interface. The data’s are displayed in ascending order.

To implement the program as follows.

  • ·       Include the built in packages java.util.Set and java.util.TreeSet.
  • ·       Write java code for creating a class with main().
  • ·       An object is created for TreeSet.
  • ·       Using the object, add the data.
  • ·       Display the data. It automatically display it in ascending order.

Program:

   import java.util.Set;

   import java.util.TreeSet;

   public class TreeSetEg {

       public static void main(String[] args) {

           Set<String> treeSet1 = new TreeSet<>();

           treeSet1.add("Red");

           treeSet1.add("Green");

           treeSet1.add("Yellow");

           treeSet1.add("Orange");

           treeSet1.add("Blue");

           treeSet1.add("Green"); // it is a duplicate data, it is not added in the set

            System.out.println(treeSet1);

       }

   }

Output:

C:\raji\blog>javac TreeSetEg.java

C:\raji\blog>java TreeSetEg

[Blue, Green, Orange, Red, Yellow]

This is the basic implementation of Set interface in java.

Java program to find the top k frequent elements

Problem: To find the top K frequent elements in an array.

It uses HashMap technique and a priority queue. HashMap is for counting the frequency. Priority queue is implemented as min-heap. It helps to check the top k elements.

Method:

There are two data structures and one function

Data Structures:

Priority Queue: It acts as a Min-Heap from which has the top k frequent elements.  Min-Heap is suitable for this problem.it handles smallest frequency efficiently.

Frequency Map: It holds the count of the frequency of each elements in the array.

Function:

It checks the heap which contains the top k frequent element and extract it for display.

Program:

import java.util.HashMap;

import java.util.Map;

import java.util.PriorityQueue;

public class TopKFrequentElementsEg {

    public static int[] topKFrequent(int[] nos, int k) {

        // let us Count the frequency of each element

        Map<Integer, Integer> fMap = new HashMap<>();

        for (int no : nos) {

            fMap.put(no, fMap.getOrDefault(no, 0) + 1);

        }

        // A priority queue (min-heap) is used to keep track of top k elements

        PriorityQueue<Map.Entry<Integer, Integer>> minHeap1 = new PriorityQueue<>((a, b) ->   

        a.getValue() - b.getValue());

        for (Map.Entry<Integer, Integer> entry : fMap.entrySet()) {

            minHeap1.offer(entry);

            if (minHeap1.size() > k) {

                minHeap1.poll();

            }

        }

         // Extract the elements from the priority queue

        int[] topKElements = new int[k];

        int index = 0;

        while (!minHeap1.isEmpty()) {

            topKElements[index++] = minHeap1.poll().getKey();

        }

      return topKElements;

    }

    public static void main(String[] args) {

        int[] nos = {11, 11, 11, 22, 22, 33};

        int k = 2;

        int[] result = topKFrequent(nos, k);

       //Let us dispaly the result

        for (int no : result) {

            System.out.print(no + " ");

        }

    }

}

Output:

C:\raji\blog>javac TopKFrequentElementsEg.java

C:\raji\blog>java TopKFrequentElementsEg

22 11

This is the efficient implementation of finding the top k frequent elements in an array. Keep coding!!!

Java Program to Rotate a queue by ‘K’ position

              Queue is a linear data structure. It has a front end which points out the beginning and rear end which points out the ending of the queue.

Generally, deletion occurs in front end. Insertions occurs in rear end.

Process:

  • First , a java class is written with a constructor.  x
  • We create a queue as linked list and declare an object instance.
  • The constructor checks the ‘k’ value and rotates the queue by moving the front end element to rear end until the ‘k’th element as front end.
  • Inside the main function, create an object for queue. The data’s are inserted in the queue.
  • The input value is received from user. The queue object and k value is passed to the function.
  • The function returns the rotated queue  and it is displayed in the output screen.

Program:

import java.util.LinkedList;

import java.util.Queue;

import java.util.Scanner;

public class RotateaQueue {

    // function definition for rotation

    public static void rotateaQueue(Queue<Integer> queue1, int k) {

        int q_size = queue1.size();

        k = k % q_size;

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

            // Let us move the frontend element to the rearend

            int frontend = queue1.poll();

            queue1.add(frontend);

        }

    }

    public static void main(String[] args) {

        Queue<Integer> queue1 = new LinkedList<>();

        Scanner myObj1 = new Scanner(System.in);

        queue1.add(11);

        queue1.add(32);

        queue1.add(25);

        queue1.add(40);

        queue1.add(15);

        queue1.add(20);

        System.out.println("Enter the K value from which the queue is going to be rotated:");

        int k= myObj1.nextInt();

        System.out.println("Original Queue: " + queue1);

        rotateaQueue(queue1, k);

        System.out.println("Rotated Queue: " + queue1);

    }

}

Output:

C:\raji\blog>java RotateaQueue

Enter the K value from which the queue is going to be rotated:

4

Original Queue: [11, 32, 25, 40, 15, 20]

Rotated Queue: [15, 20, 11, 32, 25, 40]

That’s all. The java program to implement the rotatation of  a queue by k positions is running successfully. Keep coding!!!