Map interface in Java .
Hi All,
This article is all about Map interface in Java.I think you heard about Map interface before and there are other 2 interfaces in Java collection framework,Set and List .But Map is not inside Collection interface.Let’s dive in map interface and get to know its features.I learn this concepts in my 1 year in uni and also refreshed my knowledge about DSA using Amazon Cousera Java Junior Developer Professional Certificate.Anyone interested to learn DSA ,you can try above certs for improve your knowledge and this knowledge is very helpful to ace any computer science interviews.
Let’s start.First Map is not part of Collection interface in Java So we cannot use collection features like add (),addAll() methods instead we can use Put() and get() and so many other method related to Map interface.
You may know map interface has key,value pairs to store their data and each key is unique avoiding entry of redundant key to this data structure.
We can add one null key and any same values for value place, But one unique value for whole data structure.
In Map interface there are 3 classes implement this map interface and there are,
- HashMap
- LinkedHashMap
- TreeMap
Those are from Map interface and it all inherits map class’s features.That is beauty of OOP language.
First Discuss about HashMap,
HashMap.
Before enrolling Amazon Junior Developer course ,I didn’t know about treemap and linkedHashMap . I only know hashMap and I applied everytime when I see unique and Constant timing process for adding ,searching and deleting process in scenarios.After that I came to know there are other 2 classes.
In HashMap class ,it has feature of constant time for add,remove,search in this struture . That’s good and optimize solution for scenarioes. It used hash array for maintaining unique keys its values, equal time for any keys. But it doesn’t maintaining insertion order stored data,in other words hashMap struture doesn’t maintaining sorted order for storing keys and values.
HashMap’s key is assuming the hash function disperses the elements properly among the buckets.
All add,remove,fetch take constant time O(1).We can use display hashmap using keySet() iteration and entrySet iterations.
public class HashMapIteration {
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
map.put("LY2048303", "John Wells");
map.put("AB0649858", "Lori Wells");
map.put("AB4453455", "David Windston");
map.put("CS9857859", "John Smith");
map.put("LY9475958", "Alen Cornworth");
System.out.println();
//using keySet
Set<String> keys = map.keySet();
for (String key : keys) {
String value = map.get(key);
System.out.println("ID: " + key + ", NAME: " + value);
}
System.out.println();
//Another way
for (Object key : keys) {
Object value = hashMap.get(key);
System.out.println("ID: " + key + ", NAME: " + value);
}
//using entrySet
Set entries = map.entrySet();
for (Object entry : entries) {
Map.Entry mapEntry = (Map.Entry) entry;
Object key = mapEntry.getKey();
Object value = mapEntry.getValue();
System.out.println("ID: " + key + ", NAME: " + value);
}
}
}You can get more example based on real world example in here.
That’s all about HashMap class.Next topic is LinkedHashMap class.
LinkedHashMap.
You may heard about linkedList and this is not equal,this data stucture offers the efficency of a HashMap but also maintained a consistent order of elements, and this LinkedHashMap is overcome issue with insertion order in HashMap class and add more features to maintain our data .
This is doubly linked list running through all entries and maintain insertion order in keys.
Get Heshan Umayanga’s stories in your inbox
Join Medium for free to get updates from this writer.
Features of LinkedMap,
- Maintaining insertion order
- Supports null values and keys.
- Provides predictable iteration.
And there are some features only in linkedHashMap class,put,get,remove,containsm,entryset .And other features include as hashMap,speciality is maintaining insertion order for keys.
public class Main {
public static void main(String[] args) {
LinkedHashMap<String, Integer> studentScores = new LinkedHashMap<>();
// Adding initial scores
studentScores.put("Alice", 85);
studentScores.put("Bob", 90);
studentScores.put("Charlie", 78);
// Displaying all scores
System.out.println("Initial Scores:");
for (Map.Entry<String, Integer> entry : studentScores.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
// Updating Bob's score
studentScores.put("Bob", 95);
// Checking if Charlie is in the list
if (studentScores.containsKey("Charlie")) {
System.out.println("Charlie's score: " + studentScores.get("Charlie"));
}
// Removing Charlie from the list
studentScores.remove("Charlie");
// Adding a new student if not already present
studentScores.putIfAbsent("David", 92);
// Displaying the final scores
System.out.println("\nFinal Scores:");
for (Map.Entry<String, Integer> entry : studentScores.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}OutPut is below,
Initial Scores:
Alice: 85
Bob: 90
Charlie: 78
Charlie's score: 78
Final Scores:
Alice: 85
Bob: 95
David: 92You can find real world example solution using linkedHashMap here.I think this will enough for linkedHashMap.
TreeMap.
Implements the NavigatableMap interface and stores key-value pairs in a sorted order, based on the natural ordering of the keys or a specified comparator.
It provides guaranteed log(n) time cost for most operations and it use black red binary tree to balanced tree .So that O(logn) due to binary tree.
It is maintaing natural order for keys,ascending order for numeric values and A-Z order to String values for keys.We don’t want to pay sorting our data base on our key, TreeMap support natural order and it will order our data according to natural order.
It has methods from map interface and own methods like firstKey(),lastKey,,higheeKey,lowerkey .
import java.util.TreeMap;
public class EventSchedule {
public static void main(String[] args) {
TreeMap<String, String> schedule = new TreeMap<>();
// Adding sessions to the schedule
schedule.put("09:00", "Dr. Smith - AI Trends");
schedule.put("10:30", "Ms. Johnson - Data Privacy");
schedule.put("11:45", "Mr. Lee - Cloud Computing");
System.out.println("Conference Schedule: " + schedule);
}
}this class takes O log(n) time for add ,delete fetch data,but preserve natural order for keys.
You can find real world example and solution here.
To sum up,
- HashMap is typical for frequently modifying data it takes constant time for any operation O(1).But doesn’t maintaing order.
- LinkHashMap-this is best for maintaing order related scenarios,
- TreeMap-used for maintaing natural order scenarios and it takes O(logn) for every operations.
So please be advised to use related map classes depend on scenarios.
Don’t use hashMap to apply every solutions.:)
I think this content is enough for this map interface article ,Happy coding;
References:Amzon Junior Developer (DSA)courses









