package adddingcutomobjectinlinkedhashmap; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import java.util.TreeMap; 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> linkedHashMapObj = new LinkedHashMap<>(); 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"); linkedHashMapObj.put(b1, "auther1"); linkedHashMapObj.put(b2, "auther2"); linkedHashMapObj.put(b3, "auther3"); linkedHashMapObj.put(b4, "auther4"); linkedHashMapObj.put(b5, "auther5"); Set<Map.Entry<Book, String>> set = linkedHashMapObj.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 3 book name is godan
auther is auther2
book id is 4 book name is gaban
auther is auther3
book id is 2 book name is mahabharta
auther is auther4
book id is 2 book name is ramayana
auther is auther5