0% found this document useful (0 votes)
40 views13 pages

Map Interface

Map Interface in Java pdf

Uploaded by

tstudent437
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views13 pages

Map Interface

Map Interface in Java pdf

Uploaded by

tstudent437
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 13

Map interface

__________________________________________________________________
Map interface is same like as collection but not part of Collection and which is used for store data in the
form of key and value pair key cannot be duplicated but value may be duplicated using key we can store
data in map , retrieve data from map as well as delete data from map etc
Map is combination of list and set collection set maintain the key data and list maintain value and
normally map recommended when we want to maintain the uniqueness in duplicated data.

Example of Map

If we want to work with Map interface we have to use following Hierarchy

If we think about above hierarchy we have Map interface and Map interface provide some inbuilt
method to us for store data as well as retrieve data as well as perform different operation on Map
interface.

Methods of Map interface


public abstract V put (K, V): this method can store data in key and value pair.
V get(K key): this method is used for retrieve data from map using its key and if key not found return
null value.
Note: this method can use for two purposes.
1. for Fetch Record from Map

2. for Search Record from Map.

V remove(java.lang.Object key): this method can remove data from map using its key and if key not
found return null
Note:Normally when we want to remove data from map first ensure data present in map by using get()
methods

boolean containsKey(Object key): this method is used for search key in map if key found return true
otherwise return false.
boolean containsValue(Object value): this method check value present in map or not if present return
true otherwise return false.

Set keySet(): this method can fetch all keys from map and store in Set collection.
Note: we can fetch this method for fetch all data from Map Collection
Collection values(): this method is used for fetch all values from map Collection.

public Set<Map.Entry> entrySet(): this method can fetch all keys and value from map by using
Map.Entry interface.
So Map.Entry interface provide some inbuilt method to us
Object getKey(): this method is used for return key from map.
Object getValue(): this method is used for return value from map.

Example: we want to fetch all methods from Map collection

Now we want to discuss about types of Map


HashMap: HashMap can store data in the form of key and value pair and generate key sequence
randomly
LinkedHashMap: LinkedHashMap can store data in the form of key and value pair and generate key
sequence as per the user sequence.
TreeMap: TreeMap can store data in the form of key and value pair and generate key sequence in
ascending order.
Now we want to discuss about the constructor of HashMap
HashMap(): this constructor create HashMap with default capacity 16 and load factor with 0.75
public HashMap(int initialCapacity) : this constructor is used for create map with initial capacity set by
developer with default load factory 0.75
public HashMap(int initialCapacity, float loadFactor): this constructor is used for create map with intial
capactiy and initial load factor value as per the user choice.
public HashMap(Map<? extends K, ? extends V> m): this constructor can accept data from another
map and copy in HashMap object.

Now we want to discuss about LinkedHashMap


LinkedHashMap is child ofHashMap and generate data sequence as per user sequence.

Constructor of LinkedHashMap
_______________________________________________________________________________
LinkedHashMap(): create LinkedHashMap with initial capacity 16 and load factory 0.75
LinkedHashMap(int intialCapacity): this constructor create LinkedHashMap with initial capacity 16.
LinkedHashMap(int initialCapacity,float loadfactor): this constructor create LinkedHashMap with
initialcapacity as per user choid and loadfactor as per user choice.
Note: if we think about above code we get key sequence as per the user sequence.

Now we want to discuss about TreeMap


___________________________________________________________________________
TreeMap(): this constructor can sort map data by using its key If key is primitive type.
means integer ,float etc

TreeMap(Comparator): this consturctor can arrange key in asending order when we have user defined
class object as key

Suppose consider we have Product list with its Feature list and we want to store product info in
TreeMap and some time we required to sort feature of product by product id or some time want to sort
feature of by product name.
So we want to perform this task by using TreeMap

Example with source code

package org.techhub.map;

public class Product {


private int id;
private String name;

public Product(String name,int id) {


this.name=name;
this.id=id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

}
package org.techhub.map;

import java.util.Comparator;

public class SortProductById implements Comparator<Product> {

@Override
public int compare(Product o1, Product o2) {
if(o1.getId()>o2.getId()) {
return 1;
}
else if(o1.getId()<o2.getId()) {
return -1;
}
else {
return 0;
}
}

package org.techhub.map;
import java.util.*;
public class TreeMapApplication {

public static void main(String x[]) {

SortProductById spid=new SortProductById();


TreeMap<Product,String> t = new TreeMap<Product,String>(spid);
Product p1=new Product("A",1);
Product p2=new Product("G",5);
Product p3=new Product("C",3);
Product p4=new Product("F",4);
Product p5=new Product("D",2);
Product p6=new Product("B",6);
t.put(p1, "good product quality");
t.put(p2, "XYZ");
t.put(p3, "MNO");
t.put(p4, "PQR");
t.put(p5, "STV");
t.put(p6, "POST");
Set<Map.Entry<Product, String>> set=t.entrySet();
for(Map.Entry<Product, String> m:set) {
Product p=m.getKey();
String value=m.getValue();
System.out.println(p.getId()+"\t"+value);
}

}
}

Example: Write a Program to Create Student Record using map collection so here rollno consider as key
and name consider value and perform following task on map.

Case 1: Insert new record in map


Case 2: View All Record frommap
Case 3: Delete record using its key
Case 4: Search record from map by value

import java.util.*;
public class MapOperationApp
{
public static void main(String x[])
{
LinkedHashMap<Integer,String> map = new LinkedHashMap<Integer,String>();
do{
Scanner xyz = new Scanner(System.in);
System.out.println("1:Insert Record in Map");
System.out.println("2:View All Record");
System.out.println("3:Delete record by using key");
System.out.println("4:Search Record by using map");
int choice;
System.out.println("Enter your choice");
choice=xyz.nextInt();
switch(choice)
{
case 1:
System.out.println("Enter roll number of student");
int roll=xyz.nextInt();
xyz.nextLine();
boolean b=map.containsKey(roll);
if(b){
System.out.println("Roll no already present");
}
else{
System.out.println("Enter name of student");
String name=xyz.nextLine();
map.put(roll,name);
System.out.println("New Student Record Added Successfully....");
}
break;
case 2:
Set<Map.Entry<Integer,String>> set=map.entrySet();
System.out.println("Student Id \t Student Name");
for(Map.Entry m:set)
{
System.out.println(m.getKey()+"\t\t"+m.getValue());
}
break;
case 3:
System.out.println("enter roll no for delete");
int rollno=xyz.nextInt();
b=map.containsKey(rollno);
if(b)
{ String s=map.remove(rollno);
System.out.println("Deleted record is "+s);
}
else{
System.out.println("Key not found");
}
break;
case 4:
xyz.nextLine();
System.out.println("Search student record by name");
String sname=xyz.nextLine();
b=map.containsValue(sname);
if(b)
{ System.out.println("Student record found");
}
else{
System.out.println("Student record not found");
}
break;
default:
System.out.println("Wrong choice");
}
}while(true);
}
}

Example: WAP to create array of size 10 and find the occurrence of every number
package org.techhub.map;
import java.util.*;
public class OccurenceOfNumberByMap {
public static void main(String[] args) {
int a[]=new int[10];
Scanner xyz = new Scanner(System.in);
System.out.println("Enter number ");
for(int i=0;i<a.length;i++)
{ a[i]=xyz.nextInt();
}
System.out.println("display array");
for(int i=0;i<a.length;i++) {
System.out.print(a[i]+"\t");
}
System.out.println();
LinkedHashMap<Integer,Integer> map = new LinkedHashMap<Integer,Integer>();
for(int i=0;i<a.length;i++) {
Integer count=map.get(a[i]);
if(count==null) {
count=new Integer(0);
}
++count;
map.put(a[i], count);
}
System.out.println("Display all values from map");
Set<Map.Entry<Integer, Integer>> set=map.entrySet();
for(Map.Entry<Integer, Integer> m:set) {
System.out.println(m.getKey()+"\t"+m.getValue());
}
}
}

Example: WAP to input the string from keyboard find the repeat word from string.

good morning india good afternoon india good evening pune

package org.techhub.map;
import java.util.*;
public class FindDuplicateWordFromString {

public static void main(String x[]) {


Scanner xyz = new Scanner(System.in);
System.out.println("Enter string from keyboard");
String str=xyz.nextLine();
String words[]=str.split(" ");
LinkedHashMap<String,Integer> map= new LinkedHashMap<String,Integer>();
for(String s:words)
{
Integer count=map.get(s);
if(count==null) {
count = new Integer(0);
}
++count;
map.put(s, count);
}
System.out.println("Display duplicated words");
Set<Map.Entry<String, Integer>> set=map.entrySet();
for(Map.Entry<String, Integer> m:set) {
if(m.getValue()>1) {
System.out.println(m.getKey()+"\t"+m.getValue());
}
}
}
}
Example with source code
package org.techhub.map;
import java.util.*;
public class TeamPlayerApplication {
public static void main(String[] args) {
LinkedHashMap<String, ArrayList<String>> map = new
LinkedHashMap<String,ArrayList<String>>();

ArrayList<String> indPList=new ArrayList<String>();


indPList.add("Rohit");
indPList.add("Virat");
indPList.add("Dhoni");

ArrayList<String> ausPList=new ArrayList<String>();


ausPList.add("Cummunis");
ausPList.add("Warnar");
ausPList.add("Travis");

map.put("India", indPList);
map.put("Aus", ausPList);
Set<Map.Entry<String, ArrayList<String>>> set=map.entrySet();
for(Map.Entry<String,ArrayList<String>> m:set) {
String teamName=m.getKey();
ArrayList<String> plist=m.getValue();
System.out.println(teamName);
System.out.println("===============================");
for(String pname:plist) {
System.out.println(pname);
}
System.out.println();
System.out.println();
}
}

Example: WAP to Create Map and store student details in it.

Perform following operation on above map.


1. Student new student data
2. View All Student Data
3. Search Student data by name
4. Search Student by PRN
5. Delete Student by CourseName
6. Find the course wise student data
7. Find the course wise student count
8. Arrange Student count course wise in descending order.

You might also like