package addingcustomonjectinhashtable; import java.util.*; class Book { private String bookName; private int id; public Book(int id, String bookName) { super(); this.id = id; this.bookName = bookName; } public String getBookName() { return bookName; } public void setBookName(String bookName) { this.bookName = bookName; } public int getId() { return id; } public void setId(int id) { this.id = id; } } public class Example { public static void main(String[] args) { Map<Book,String> hashtableObj = new Hashtable<>(); Book b1 = new Book(2,"alchemist"); Book b2 = new Book(3,"godan"); Book b3 = new Book(4,"gaban"); Book b4 = new Book(2,"mahabharta"); Book b5 = new Book(2,"ramayana"); hashtableObj.put(b1, "auther1"); hashtableObj.put(b2, "auther2"); hashtableObj.put(b3, "auther3"); hashtableObj.put(b4, "auther4"); hashtableObj.put(b5, "auther5"); Set<Map.Entry<Book, String>> set = hashtableObj.entrySet(); for(Map.Entry<Book, String> entry : set) { Book book = entry.getKey(); String auther = entry.getValue(); System.out.println("book id is "+book.getId() +" "+"book name is "+book.getBookName()); System.out.println("auther is " +auther); } } }
Output is –
book id is 2 book name is alchemist
auther is auther1
book id is 2 book name is ramayana
auther is auther5
book id is 2 book name is mahabharta
auther is auther4
book id is 4 book name is gaban
auther is auther3
book id is 3 book name is godan
auther is auther2