Write a Java program using Map interface containing list of items having keys andassociated values and perform the following operations:
Add items in the
Remove items from the map
Search specific key from the map
Get value of the specified key
Insert map elements of one map in to other
Print all keys and values of the map.
Code:- 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;
}
}
Code :- mapExample.java
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");
Book b=new Book();
//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());
}
}
}
Output
101 Let us C Yashwant Kanetkar
102 Data communication & Networking Forouzan 103 Operating System Achuyut Godbole
Traversing map after removing 2nd element
101 Let us C Yashwant Kanetkar
103 Operating System Achuyut Godbole Enter the key 101
101 Let us C Yashwant Kanetkar