Deep dive into LinkedHashMap and TreeMap

Last updated on Dec 23 2022
Prabhas Ramanathan

java 31

Java LinkedHashMap class is Hashtable and Linked list implementation of the Map interface, with predictable iteration order. It inherits HashMap class and implements the Map interface.

Table of Contents

Points to remember

• Java LinkedHashMap contains values based on the key.
• Java LinkedHashMap contains unique elements.
• Java LinkedHashMap may have one null key and multiple null values.
• Java LinkedHashMap is non synchronized.
• Java LinkedHashMap maintains insertion order.
• The initial default capacity of Java HashMap class is 16 with a load factor of 0.75.

LinkedHashMap class declaration

Let’s see the declaration for java.util.LinkedHashMap class.
1. public class LinkedHashMap<K,V> extends HashMap<K,V> implements Map<K,V>

LinkedHashMap class Parameters

Let’s see the Parameters for java.util.LinkedHashMap class.
• K: It is the type of keys maintained by this map.
• V: It is the type of mapped values.

Constructors of Java LinkedHashMap class

Constructor Description
LinkedHashMap() It is used to construct a default LinkedHashMap.
LinkedHashMap(int capacity) It is used to initialize a LinkedHashMap with the given capacity.
LinkedHashMap(int capacity, float loadFactor) It is used to initialize both the capacity and the load factor.
LinkedHashMap(int capacity, float loadFactor, boolean accessOrder) It is used to initialize both the capacity and the load factor with specified ordering mode.
LinkedHashMap(Map<? extends K,? extends V> m) It is used to initialize the LinkedHashMap with the elements from the given Map class m.

Methods of Java LinkedHashMap class

Method Description
V get(Object key) It returns the value to which the specified key is mapped.
void clear() It removes all the key-value pairs from a map.
boolean containsValue(Object value) It returns true if the map maps one or more keys to the specified value.
Set<Map.Entry<K,V>> entrySet() It returns a Set view of the mappings contained in the map.
void forEach(BiConsumer<? super K,? super V> action) It performs the given action for each entry in the map until all entries have been processed or the action throws an exception.
V getOrDefault(Object key, V defaultValue) It returns the value to which the specified key is mapped or defaultValue if this map contains no mapping for the key.
Set<K> keySet() It returns a Set view of the keys contained in the map
protected boolean removeEldestEntry(Map.Entry<K,V> eldest) It returns true on removing its eldest entry.
void replaceAll(BiFunction<? super K,? super V,? extends V> function) It replaces each entry’s value with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception.
Collection<V> values() It returns a Collection view of the values contained in this map.

Java LinkedHashMap Example

1. import java.util.*;
2. class LinkedHashMap1{
3. public static void main(String args[]){
4.
5. LinkedHashMap<Integer,String> hm=new LinkedHashMap<Integer,String>();
6.
7. hm.put(100,”Amit”);
8. hm.put(101,”Vijay”);
9. hm.put(102,”Rahul”);
10.
11. for(Map.Entry m:hm.entrySet()){
12. System.out.println(m.getKey()+” “+m.getValue());
13. }
14. }
15. }
Output:100 Amit
101 Vijay
102 Rahul

Java LinkedHashMap Example: Key-Value pair

1. import java.util.*;
2. class LinkedHashMap2{
3. public static void main(String args[]){
4. LinkedHashMap<Integer, String> map = new LinkedHashMap<Integer, String>();
5. map.put(100,”Amit”);
6. map.put(101,”Vijay”);
7. map.put(102,”Rahul”);
8. //Fetching key
9. System.out.println(“Keys: “+map.keySet());
10. //Fetching value
11. System.out.println(“Values: “+map.values());
12. //Fetching key-value pair
13. System.out.println(“Key-Value pairs: “+map.entrySet());
14. }
15. }
Keys: [100, 101, 102]
Values: [Amit, Vijay, Rahul]
Key-Value pairs: [100=Amit, 101=Vijay, 102=Rahul]

Java LinkedHashMap Example:remove()

1. import java.util.*;
2. public class LinkedHashMap3 {
3. public static void main(String args[]) {
4. Map<Integer,String> map=new LinkedHashMap<Integer,String>();
5. map.put(101,”Amit”);
6. map.put(102,”Vijay”);
7. map.put(103,”Rahul”);
8. System.out.println(“Before invoking remove() method: “+map);
9. map.remove(102);
10. System.out.println(“After invoking remove() method: “+map);
11. }
12. }
Output:
Before invoking remove() method: {101=Amit, 102=Vijay, 103=Rahul}
After invoking remove() method: {101=Amit, 103=Rahul}

Java LinkedHashMap Example: Book

1. import java.util.*;
2. class Book {
3. int id;
4. String name,author,publisher;
5. int quantity;
6. public Book(int id, String name, String author, String publisher, int quantity) {
7. this.id = id;
8. this.name = name;
9. this.author = author;
10. this.publisher = publisher;
11. this.quantity = quantity;
12. }
13. }
14. public class MapExample {
15. public static void main(String[] args) {
16. //Creating map of Books
17. Map<Integer,Book> map=new LinkedHashMap<Integer,Book>();
18. //Creating Books
19. Book b1=new Book(101,”Let us C”,”Yashwant Kanetkar”,”BPB”,8);
20. Book b2=new Book(102,”Data Communications & Networking”,”Forouzan”,”Mc Graw Hill”,4);
21. Book b3=new Book(103,”Operating System”,”Galvin”,”Wiley”,6);
22. //Adding Books to map
23. map.put(2,b2);
24. map.put(1,b1);
25. map.put(3,b3);
26.
27. //Traversing map
28. for(Map.Entry<Integer, Book> entry:map.entrySet()){
29. int key=entry.getKey();
30. Book b=entry.getValue();
31. System.out.println(key+” Details:”);
32. System.out.println(b.id+” “+b.name+” “+b.author+” “+b.publisher+” “+b.quantity);
33. }
34. }
35. }
Output:
2 Details:
102 Data Communications & Networking Forouzan Mc Graw Hill 4
1 Details:
101 Let us C Yashwant Kanetkar BPB 8
3 Details:
103 Operating System Galvin Wiley 6

Java TreeMap class

java 32

Java TreeMap class is a red-black tree based implementation. It provides an efficient means of storing key-value pairs in sorted order.
The important points about Java TreeMap class are:
• Java TreeMap contains values based on the key. It implements the NavigableMap interface and extends AbstractMap class.
• Java TreeMap contains only unique elements.
• Java TreeMap cannot have a null key but can have multiple null values.
• Java TreeMap is non synchronized.
• Java TreeMap maintains ascending order.

TreeMap class declaration

Let’s see the declaration for java.util.TreeMap class.
1. public class TreeMap<K,V> extends AbstractMap<K,V> implements NavigableMap<K,V>, Cloneable, Serializable

TreeMap class Parameters

Let’s see the Parameters for java.util.TreeMap class.
• K: It is the type of keys maintained by this map.
• V: It is the type of mapped values.

Constructors of Java TreeMap class

Constructor Description
TreeMap() It is used to construct an empty tree map that will be sorted using the natural order of its key.
TreeMap(Comparator<? super K> comparator) It is used to construct an empty tree-based map that will be sorted using the comparator comp.
TreeMap(Map<? extends K,? extends V> m) It is used to initialize a treemap with the entries from m, which will be sorted using the natural order of the keys.
TreeMap(SortedMap<K,? extends V> m) It is used to initialize a treemap with the entries from the SortedMap sm, which will be sorted in the same order as sm.

Methods of Java TreeMap class

Method Description
Map.Entry<K,V> ceilingEntry(K key) It returns the key-value pair having the least key, greater than or equal to the specified key, or null if there is no such key.
K ceilingKey(K key) It returns the least key, greater than the specified key or null if there is no such key.
void clear() It removes all the key-value pairs from a map.
Object clone() It returns a shallow copy of TreeMap instance.
Comparator<? super K> comparator() It returns the comparator that arranges the key in order, or null if the map uses the natural ordering.
NavigableSet<K> descendingKeySet() It returns a reverse order NavigableSet view of the keys contained in the map.
NavigableMap<K,V> descendingMap() It returns the specified key-value pairs in descending order.
Map.Entry firstEntry() It returns the key-value pair having the least key.
Map.Entry<K,V> floorEntry(K key) It returns the greatest key, less than or equal to the specified key, or null if there is no such key.
void forEach(BiConsumer<? super K,? super V> action) It performs the given action for each entry in the map until all entries have been processed or the action throws an exception.
SortedMap<K,V> headMap(K toKey) It returns the key-value pairs whose keys are strictly less than toKey.
NavigableMap<K,V> headMap(K toKey, boolean inclusive) It returns the key-value pairs whose keys are less than (or equal to if inclusive is true) toKey.
Map.Entry<K,V> higherEntry(K key) It returns the least key strictly greater than the given key, or null if there is no such key.
K higherKey(K key) It is used to return true if this map contains a mapping for the specified key.
Set keySet() It returns the collection of keys exist in the map.
Map.Entry<K,V> lastEntry() It returns the key-value pair having the greatest key, or null if there is no such key.
Map.Entry<K,V> lowerEntry(K key) It returns a key-value mapping associated with the greatest key strictly less than the given key, or null if there is no such key.
K lowerKey(K key) It returns the greatest key strictly less than the given key, or null if there is no such key.
NavigableSet<K> navigableKeySet() It returns a NavigableSet view of the keys contained in this map.
Map.Entry<K,V> pollFirstEntry() It removes and returns a key-value mapping associated with the least key in this map, or null if the map is empty.
Map.Entry<K,V> pollLastEntry() It removes and returns a key-value mapping associated with the greatest key in this map, or null if the map is empty.
V put(K key, V value) It inserts the specified value with the specified key in the map.
void putAll(Map<? extends K,? extends V> map) It is used to copy all the key-value pair from one map to another map.
V replace(K key, V value) It replaces the specified value for a specified key.
boolean replace(K key, V oldValue, V newValue) It replaces the old value with the new value for a specified key.
void replaceAll(BiFunction<? super K,? super V,? extends V> function) It replaces each entry’s value with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception.
NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) It returns key-value pairs whose keys range from fromKey to toKey.
SortedMap<K,V> subMap(K fromKey, K toKey) It returns key-value pairs whose keys range from fromKey, inclusive, to toKey, exclusive.
SortedMap<K,V> tailMap(K fromKey) It returns key-value pairs whose keys are greater than or equal to fromKey.
NavigableMap<K,V> tailMap(K fromKey, boolean inclusive) It returns key-value pairs whose keys are greater than (or equal to, if inclusive is true) fromKey.
boolean containsKey(Object key) It returns true if the map contains a mapping for the specified key.
boolean containsValue(Object value) It returns true if the map maps one or more keys to the specified value.
K firstKey() It is used to return the first (lowest) key currently in this sorted map.
V get(Object key) It is used to return the value to which the map maps the specified key.
K lastKey() It is used to return the last (highest) key currently in the sorted map.
V remove(Object key) It removes the key-value pair of the specified key from the map.
Set<Map.Entry<K,V>> entrySet() It returns a set view of the mappings contained in the map.
int size() It returns the number of key-value pairs exists in the hashtable.
Collection values() It returns a collection view of the values contained in the map.

Java TreeMap Example

1. import java.util.*;
2. class TreeMap1{
3. public static void main(String args[]){
4. TreeMap<Integer,String> map=new TreeMap<Integer,String>();
5. map.put(100,”Amit”);
6. map.put(102,”Ravi”);
7. map.put(101,”Vijay”);
8. map.put(103,”Rahul”);
9.
10. for(Map.Entry m:map.entrySet()){
11. System.out.println(m.getKey()+” “+m.getValue());
12. }
13. }
14. }
Output:100 Amit
101 Vijay
102 Ravi
103 Rahul

Java TreeMap Example: remove()

1. import java.util.*;
2. public class TreeMap2 {
3. public static void main(String args[]) {
4. TreeMap<Integer,String> map=new TreeMap<Integer,String>();
5. map.put(100,”Amit”);
6. map.put(102,”Ravi”);
7. map.put(101,”Vijay”);
8. map.put(103,”Rahul”);
9. System.out.println(“Before invoking remove() method”);
10. for(Map.Entry m:map.entrySet())
11. {
12. System.out.println(m.getKey()+” “+m.getValue());
13. }
14. map.remove(102);
15. System.out.println(“After invoking remove() method”);
16. for(Map.Entry m:map.entrySet())
17. {
18. System.out.println(m.getKey()+” “+m.getValue());
19. }
20. }
21. }
Output:
Before invoking remove() method
100 Amit
101 Vijay
102 Ravi
103 Rahul
After invoking remove() method
100 Amit
101 Vijay
103 Rahul

Java TreeMap Example: NavigableMap

1. import java.util.*;
2. class TreeMap3{
3. public static void main(String args[]){
4. NavigableMap<Integer,String> map=new TreeMap<Integer,String>();
5. map.put(100,”Amit”);
6. map.put(102,”Ravi”);
7. map.put(101,”Vijay”);
8. map.put(103,”Rahul”);
9. //Maintains descending order
10. System.out.println(“descendingMap: “+map.descendingMap());
11. //Returns key-value pairs whose keys are less than or equal to the specified key.
12. System.out.println(“headMap: “+map.headMap(102,true));
13. //Returns key-value pairs whose keys are greater than or equal to the specified key.
14. System.out.println(“tailMap: “+map.tailMap(102,true));
15. //Returns key-value pairs exists in between the specified key.
16. System.out.println(“subMap: “+map.subMap(100, false, 102, true));
17. }
18. }
descendingMap: {103=Rahul, 102=Ravi, 101=Vijay, 100=Amit}
headMap: {100=Amit, 101=Vijay, 102=Ravi}
tailMap: {102=Ravi, 103=Rahul}
subMap: {101=Vijay, 102=Ravi}

Java TreeMap Example: SortedMap

1. import java.util.*;
2. class TreeMap4{
3. public static void main(String args[]){
4. SortedMap<Integer,String> map=new TreeMap<Integer,String>();
5. map.put(100,”Amit”);
6. map.put(102,”Ravi”);
7. map.put(101,”Vijay”);
8. map.put(103,”Rahul”);
9. //Returns key-value pairs whose keys are less than the specified key.
10. System.out.println(“headMap: “+map.headMap(102));
11. //Returns key-value pairs whose keys are greater than or equal to the specified key.
12. System.out.println(“tailMap: “+map.tailMap(102));
13. //Returns key-value pairs exists in between the specified key.
14. System.out.println(“subMap: “+map.subMap(100, 102));
15. }
16. }
headMap: {100=Amit, 101=Vijay}
tailMap: {102=Ravi, 103=Rahul}
subMap: {100=Amit, 101=Vijay}
What is difference between HashMap and TreeMap?
HashMap TreeMap
1) HashMap can contain one null key. TreeMap cannot contain any null key.
2) HashMap maintains no order. TreeMap maintains ascending order.

Java TreeMap Example: Book

1. import java.util.*;
2. class Book {
3. int id;
4. String name,author,publisher;
5. int quantity;
6. public Book(int id, String name, String author, String publisher, int quantity) {
7. this.id = id;
8. this.name = name;
9. this.author = author;
10. this.publisher = publisher;
11. this.quantity = quantity;
12. }
13. }
14. public class MapExample {
15. public static void main(String[] args) {
16. //Creating map of Books
17. Map<Integer,Book> map=new TreeMap<Integer,Book>();
18. //Creating Books
19. Book b1=new Book(101,”Let us C”,”Yashwant Kanetkar”,”BPB”,8);
20. Book b2=new Book(102,”Data Communications & Networking”,”Forouzan”,”Mc Graw Hill”,4);
21. Book b3=new Book(103,”Operating System”,”Galvin”,”Wiley”,6);
22. //Adding Books to map
23. map.put(2,b2);
24. map.put(1,b1);
25. map.put(3,b3);
26.
27. //Traversing map
28. for(Map.Entry<Integer, Book> entry:map.entrySet()){
29. int key=entry.getKey();
30. Book b=entry.getValue();
31. System.out.println(key+” Details:”);
32. System.out.println(b.id+” “+b.name+” “+b.author+” “+b.publisher+” “+b.quantity);
33. }
34. }
35. }
Output:
1 Details:
101 Let us C Yashwant Kanetkar BPB 8
2 Details:
102 Data Communications & Networking Forouzan Mc Graw Hill 4
3 Details:
103 Operating System Galvin Wiley 6

So, this brings us to the end of blog. This Tecklearn ‘Deep dive into LinkedHashMap and TreeMap’ blog helps you with commonly asked questions if you are looking out for a job in Java Programming. If you wish to learn Java and build a career Java Programming domain, then check out our interactive, Java and JEE Training, that comes with 24*7 support to guide you throughout your learning period. Please find the link for course details:

Java and JEE Training

Java and JEE Training

About the Course

Java and JEE Certification Training is designed by professionals as per the industrial requirements and demands. This training encompasses comprehensive knowledge on basic and advanced concepts of core Java & J2EE along with popular frameworks like Hibernate, Spring & SOA. In this course, you will gain expertise in concepts like Java Array, Java OOPs, Java Function, Java Loops, Java Collections, Java Thread, Java Servlet, and Web Services using industry use-cases and this will help you to become a certified Java expert.

Why Should you take Java and JEE Training?

• Java developers are in great demand in the job market. With average pay going between $90,000/- to $120,000/- depending on your experience and the employers.
• Used by more than 10 Million developers worldwide to develop applications for 15 Billion devices.
• Java is one of the most popular programming languages in the software world. Rated #1 in TIOBE Popular programming languages index (15th Consecutive Year)

What you will Learn in this Course?

Introduction to Java

• Java Fundamentals
• Introduction to Java Basics
• Features of Java
• Various components of Java language
• Benefits of Java over other programming languages
• Key Benefits of Java

Installation and IDE’s for Java Programming Language

• Installation of Java
• Setting up of Eclipse IDE
• Components of Java Program
• Editors and IDEs used for Java Programming
• Writing a Simple Java Program

Data Handling and Functions

• Data types, Operations, Compilation process, Class files, Loops, Conditions
• Using Loop Constructs
• Arrays- Single Dimensional and Multi-Dimensional
• Functions
• Functions with Arguments

OOPS in Java: Concept of Object Orientation

• Object Oriented Programming in Java
• Implement classes and objects in Java
• Create Class Constructors
• Overload Constructors
• Inheritance
• Inherit Classes and create sub-classes
• Implement abstract classes and methods
• Use static keyword
• Implement Interfaces and use it

Polymorphism, Packages and String Handling

• Concept of Static and Run time Polymorphism
• Function Overloading
• String Handling –String Class
• Java Packages

Exception Handling and Multi-Threading

• Exception handling
• Various Types of Exception Handling
• Introduction to multi-threading in Java
• Extending the thread class
• Synchronizing the thread

File Handling in Java

• Input Output Streams
• Java.io Package
• File Handling in Java

Java Collections

• Wrapper Classes and Inner Classes: Integer, Character, Boolean, Float etc
• Applet Programs: How to write UI programs with Applet, Java.lang, Java.io, Java.util
• Collections: ArrayList, Vector, HashSet, TreeSet, HashMap, HashTable

Java Database Connectivity (JDBC)

• Introduction to SQL: Connect, Insert, Update, Delete, Select
• Introduction to JDBC and Architecture of JDBC
• Insert/Update/Delete/Select Operations using JDBC
• Batch Processing Transaction
• Management: Commit and Rollback

Java Enterprise Edition – Servlets

• Introduction to J2EE
• Client Server architecture
• URL, Port Number, Request, Response
• Need for servlets
• Servlet fundamentals
• Setting up a web project in Eclipse
• Configuring and running the web app with servlets
• GET and POST request in web application with demo
• Servlet lifecycle
• Servlets Continued
• Session tracking and filter
• Forward and include Servlet request dispatchers

Java Server Pages (JSP)

• Fundamentals of Java Server Page
• Writing a code using JSP
• The architecture of JSP
• JSP Continued
• JSP elements: Scriptlets, expressions, declaration
• JSP standard actions
• JSP directives
• Introduction to JavaBeans
• ServletConfig and ServletContext
• Servlet Chaining
• Cookies Management
• Session Management

Hibernate

• Introduction to Hibernate
• Introduction to ORM
• ORM features
• Hibernate as an ORM framework
• Hibernate features
• Setting up a project with Hibernate framework
• Basic APIs needed to do CRUD operations with Hibernate
• Hibernate Architecture

POJO (Plain Old Java Object)

• POJO (Plain Old Java Object)
• Persistent Objects
• Lifecycle of Persistent Object

Spring

• Introduction to Spring
• Spring Fundamentals
• Advanced Spring

Got a question for us? Please mention it in the comments section and we will get back to you.

 

0 responses on "Deep dive into LinkedHashMap and TreeMap"

Leave a Message

Your email address will not be published. Required fields are marked *