Skip to main content

Implement Maps in java

 Implement Maps in java

It contains values on the basis of key i.e. key and value pair. Each key and value pair is known as an entry. It contains only unique keys. It is useful if you have to search, update or delete elements on the basis of key.

 

Methods of Map interface

·           put(Object key,Object value)-inserts an entry into map

·           get(Object key)-returns value for specified key

·           remove(Object key)-removes an entry for the specified key

·           containsKey(Object key)-search specified key from the map

·           keySet()-returns Set view containing all keys

·           entrySet()-returns Set view containing all keys and values

·           putAll(Map m)-inserts specified map in this map.

Implementation of Map interface

·              HashMap

·              LinkedHashMap

·              TreeMap

TreeMap

It implements Map interface using a tree which provides efficient way of storing key/value pairs in sorted order

 Features

·         It contains values based on key

·         It contains only unique elements

·         It is similar to HashMap instead it store the key/value pairs in sorted order.

         Constructors

·      TreeMap()-constructs an empty treemap that will be sorted based on key

·      TreeMap(Map m)-initializes treemap with m which will be sorted based on key

        TreeMap program

import java.util.Map;//Map is interface

import java.util.Map.Entry;//Map.Entry is sub interface of Map

import java.util.TreeMap;

import java.util.Scanner;//Scanner class reads data from input stream

class Treemapnew

{

 public static void main(String[] args)

 {

  Map<Integer,String> obj=new TreeMap<Integer,String>();//Map is interface and TreeMap is class

  Scanner s=new Scanner(System.in);

  while(true)

  {

   System.out.println("1.Add");

   System.out.println("2.Remove");

   System.out.println("3.Display");

   System.out.println("4.Quit");

   System.out.println("Enter choice");

   int choice=s.nextInt();

   switch(choice)

   {

     case 1:System.out.println("Enter the key(id) to be added to treemap");

            int key=s.nextInt();

            System.out.println("Enter the value(name) to be added to treemap");

            String value=s.next();

           obj.put(key,value);//place <key,value> into treemap

            break;

     case 2:if(obj.isEmpty())//checks whether treemap is empty or not

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

            else

            {

            System.out.println("Enter the key to be removed from treemap");

            key=s.nextInt();

            if(obj.containsKey(key))//containsKey() checks whether treemap contains key or not

            {

            value=obj.get(key);

            obj.remove(key);

            System.out.println("<"+key+","+value+"> pair is removed from treemap successfully");

            }

            else

            System.out.println("Key not found in treemap to be deleted");

            }

            break;

     case 3:if(obj.isEmpty())

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

            else

            {

            System.out.println("Treemap elements");

            for( Map.Entry<Integer,String> m:obj.entrySet())

          //Map.entry interface and entrySet() returns <key,value> pair

            System.out.println(m.getKey()+","+m.getValue());

         //Object[] a=obj.keySet().toArray();//obj.keySet() returns set of keys and converts the given set into array

        //now using get(key) of TreeMap retrieve value

   /*for(int i=0;i<obj.size();++i)

   {

     System.out.println(obj.get(a[i]));

   }  */       

          }

            break;

     case 4:System.exit(0);

     default:System.out.println("Wrong choice");

    }

   }

  }

}

Expected Output

1.Add

2.Remove

3.Display

4.Quit

Enter choice

1

Enter the key(id) to be added to treemap

100

Enter the value(name) to be added to treemap

raju

1.Add

2.Remove

3.Display

4.Quit

Enter choice

1

Enter the key(id) to be added to treemap

95

Enter the value(name) to be added to treemap

ravi

1.Add

2.Remove

3.Display

4.Quit

Enter choice

1

Enter the key(id) to be added to treemap

98

Enter the value(name) to be added to treemap

venu

1.Add

2.Remove

3.Display

4.Quit

Enter choice

3

Treemap elements

95,ravi

98,venu

100,raju

1.Add

2.Remove

3.Display

4.Quit

Enter choice

2

Enter the key to be removed from treemap

96

Key not found in treemap to be deleted

1.Add

2.Remove

3.Display

4.Quit

Enter choice

2

Enter the key to be removed from treemap

95

<95,ravi> pair is removed from treemap successfully

1.Add

2.Remove

3.Display

4.Quit

Enter choice

3

Treemap elements

98,venu

100,raju

1.Add

2.Remove

3.Display

4.Quit

Enter choice

2

Enter the key to be removed from treemap

100

<100,raju> pair is removed from treemap successfully

1.Add

2.Remove

3.Display

4.Quit

Enter choice

3

Treemap elements

98,venu

1.Add

2.Remove

3.Display

4.Quit

Enter choice

2

Enter the key to be removed from treemap

98

<98,venu> pair is removed from treemap successfully

1.Add

2.Remove

3.Display

4.Quit

Enter choice

3

treemap is empty

1.Add

2.Remove

3.Display

4.Quit

Enter choice

2

Treemap is empty

1.Add

2.Remove

3.Display

4.Quit

Enter choice

4

Comments

Popular posts from this blog

Machine Learning Lab Internal Questions

 Internal Lab Programs 1. Read a CSV File, apply preprocessing, apply a few data visualizations, and train SVM model for a dataset and calculate its accuracy. Download DATASET 2. Read the CSV File, apply preprocessing, and train the data decision tree-based ID3 algorithm. Calculate each attribute value and display  3. Create a data and save it CSV, apply preprocessing by using that file demonstrate the FIND-S algorithm for finding the most specific hypothesis based on a given set of training data samples. 4. Read the super Market CSV file apply relevant visualizations (Box plot, Scatter plot, Bargraphs), linear regression and display performance metrics 5. Apply EM algorithm to cluster a set of data stored in a .CSV file. Use the same data set for clustering using k-Means algorithm. Compare the results of these two algorithms and comment on the quality of clustering. 6. Write a program for implementing Density based clustering algorithm.  7. Write a pr...

How to Install Parrot Operating System in Virtual Box using OVA

Step by Step Process of Parrot OS Installation What is Parrot OS Parrot is a free and open-source Linux system based on Debian that is popular among security researchers, security experts, developers, and privacy-conscious users. It comes with cyber security and digital forensics arsenal that is totally portable. It also includes everything you'll need to make your own apps and protect your online privacy. Parrot is offered in Home and Security Editions, as well as a virtual machine and a Docker image, featuring the KDE and Mate desktop environments. Features of Parrot OS The following are some of the features of Parrot OS that set it apart from other Debian distributions: Tor, Tor chat, I2P, Anonsurf, and Zulu Crypt, which are popular among developers, security researchers, and privacy-conscious individuals, are included as pre-installed development, forensics, and anonymity applications. It has a separate "Forensics Mode" that does not mount any of the system's hard...

Big Data Analytics Programs

  List of Programs for Big Data Analytics   CLICK ON ME 1.  Implement the following Data structures in Java       a)  Linked Lists            b)   Stacks       c)  Queues     d)   Set            e)   Map 2.  Perform setting up and Installing Hadoop in its three operating modes:      Standalone,     Pseudo distributed,     Fully distributed. 3.  Implement the following file management tasks in Hadoop:    a) Adding files and directories    b) Retrieving files    c) Deleting files 4. Run a basic Word Count Map Reduce program to understand Map Reduce Paradigm. 5. Write a Map Reduce program that mines weather data.     Weather sensors collecting data every hour at many locations across the globe gather a large volume of log data, which is a ...