Write a Java program using Map interface containing list of items having keys and associated values and perform the following operations:
1. Add items in the map.
2. Remove items from the map
3. Search specific key from the map
4. Get value of the specified key
5. Insert map elements of one map in to other map.
6. Print all keys and values of the map.
Book.java
package com.hiraymca;
/**
*
* @author VIKRAM
*/
public class Book {private int id; private String name; private String author;
public Book()
{
}
public Book(int id, String name, String author) {this.id = id;
this.name = name;
this.author = author;
}
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;
}
public String getAuthor() {return author;
}
public void setAuthor(String author) {this.author = author;
}
}
package com.hiraymca;
import java.util.HashMap; import java.util.Map;
import java.util.Scanner;
/**
*
* @author VIKRAM
*/
public class mapExample {
public static void main(String []args)
{
//Creating map of books
Map<Integer,Book>map=new HashMap<Integer,Book>();
//Creating books
Book b1=new Book(101,”Let us C”,”Yashwant Kanetkar”);
Book b2=new Book(102,”Data communication & Networking”,”Forouzan”); Book b3=new Book(103,”Operating System”,”Achuyut Godbole”);
//Adding books to map map.put(1,b1);
map.put(2,b2);
map.put(3,b3);
//Traversing the map
for(Map.Entry<Integer, Book> entry:map.entrySet()){int key=entry.getKey();
b=entry.getValue();
System.out.println(b.getId()+” “+b.getName()+” “+b.getAuthor());
}
//Removing element from map map.remove(2);
//Traversing the map after removing System.out.println();
System.out.println(“Traversing map after removing 2nd element”); for(Map.Entry<Integer, Book> entry:map.entrySet()){
int key=entry.getKey(); b=entry.getValue();
System.out.println(b.getId()+” “+b.getName()+” “+b.getAuthor());
}
//searching for specific entry int mykey;
Scanner sc=new Scanner(System.in); System.out.print(“Enter the key “); mykey=sc.nextInt();
for(Map.Entry<Integer, Book> entry:map.entrySet())
{int key=entry.getKey();
b=entry.getValue();
System.out.println(b.getId()+” “+b.getName()+” “+b.getAuthor());
}
}
}