Core Java Training
Day 13
Topics
Collection Framework
• Map
• HashMap
• TreeMap
Map Interface
The Map interface is a fundamental part of the Java Collections Framework, designed to store data in key-
value pairs.
• Key-Value Pairs: Data is stored as associations between unique keys and their corresponding
values. Each key can map to at most one value.
• Unique Keys: Duplicate keys are not permitted. If you attempt to insert an entry with an existing
key, the old value associated with that key will be replaced by the new one.
• Value Duplication: While keys must be unique, values can be duplicated across different
keys.
• No Subtype of Collection: The Map interface is not a subtype of
the Collection interface, which means it behaves differently from other collection types
like List or Set.
Map Interface
Implementations:
Since Map is an interface, you cannot directly instantiate it. You must use a class that
implements the Map interface, such as:
• HashMap: Provides fast, unordered storage and retrieval. It allows one null key and multiple
null values.
• LinkedHashMap: Maintains insertion order of elements. It also allows one null key and
multiple null values.
• TreeMap: Stores elements in a sorted order based on the natural ordering of its keys or a
custom Comparator. It generally does not allow null keys.
Map Interface
Common Operations with Map:
• put(K key, V value): Associates the specified value with the specified key in this map.
• get(Object key): Returns the value to which the specified key is mapped, or null if this map
contains no mapping for the key.
• remove(Object key): Removes the mapping for a key from this map if it is present.
• containsKey(Object key): Returns true if this map contains a mapping for the specified
key.
• containsValue(Object value): Returns true if this map maps one or more keys to the
specified value.
• size(): Returns the number of key-value mappings in this map.
• keySet(): Returns a Set view of the keys contained in this map.
• values(): Returns a Collection view of the values contained in this map.
• entrySet(): Returns a Set view of the mappings contained in this map.
Map Interface example:
// Java Program Implementing HashMap
import java.util.HashMap;
import java.util.Map;
public class NIET {
public static void main(String[] args) {
// Create a Map using HashMap
Map<String, Integer> m = new HashMap<>();
// Adding key-value pairs to the map
m.put(“Student1", 1);
m.put(“Student2", 2);
m.put(“Student3", 3);
System.out.println("Map elements: " + m);
}
}
HashMap
HashMap provides the basic implementation of the Map interface of Java. It stores the data in
(Key, Value) pairs. To access a value one must know its key. This class uses a technique
called Hashing. Hashing is a technique of converting a large String to a small String that
represents the same String. A shorter value helps in indexing and faster searches. Let's see
how to create a map object using this class.
// Java Program to illustrate the Hashmap // Inserting entries in the Map
Class // using put() method
m.put("Sweta", 10);
// Importing required classes m.put("Amiya", 30);
import java.util.*; m.put("Gudly", 20);
// Main class // Iterating over Map
public class JavaSession { for (Map.Entry<String, Integer> e
: m.entrySet())
// Main driver method
public static void main(String[] args) System.out.println(e.getKey()
{ + " "
+
// Creating an empty HashMap e.getValue());
Map<String, Integer> m = new }
HashMap<>(); }
TreeMap
The TreeMap in Java is used to implement the Map interface and NavigableMap along with
the Abstract Class. The map is sorted according to the natural ordering of its keys, or by
a Comparator provided at map creation time, depending on which constructor is used. This proves
to be an efficient way of sorting and storing the key-value pairs.
// Java Program to Illustrate // Creating an empty TreeMap
TreeMap Class Map<String, Integer> m = new TreeMap<>();
// Importing required classes // Inserting custom elements in the Map
import java.util.*; // using put() method
m.put("Sweta", 10);
// Main class m.put("Amiya", 30);
public class Geeks { m.put("Gudly", 20);
// Iterating over Map using for each loop
// Main driver method for (Map.Entry<String, Integer> e :
public static void main(String[] m.entrySet())
args) System.out.println(e.getKey() + " "
{ + e.getValue());
} }
Difference between Hashmap and TreeMap
Feature HashMap TreeMap
Ordering Unordered (random order) Sorted (based on keys)
Natural order (Comparable) or custom
Sorting Mechanism N/A
(Comparator)
Underlying Data Structure Hash Table Red-Black Tree
Key Comparison Uses hashCode() and equals() Uses compareTo() or compare()
Allows null keys Yes (only one) No (throws NullPointerException)
Allows null values Yes Yes
Thread-safe No No
Use Case Fast lookup without order Sorted keys, range views
Iterating through Map
import java.util.*;
class Hello { for (Map.Entry mapElement :
public static void main(String hm1.entrySet()) {
args[]) int key =
{ (int)mapElement.getKey();
// Initialization of a Map // Finding the value
// using Generics String value =
Map<Integer, String> hm1 (String)mapElement.getValue();
= new HashMap<Integer,
String>(); System.out.println(key + " :
" + value);
// Inserting the Elements }
hm1.put(new Integer(1), }
“Hello"); }
hm1.put(new Integer(2),
“world");
hm1.put(new Integer(3),
“Welcome");
Count the Occurrence of Numbers using Hashmap
import java.util.*; HashMap<Integer, Integer> hm = new
HashMap();
class NIET {
public static void main(String[] // counting occurrence of numbers
args) for (int i = 0; i < al.size();
{ i++) {
int a[] = { 1, 13, 4, 1, 41, 31, hm.putIfAbsent(al.get(i),
31, 4, 13, 2 }; Collections.frequency(
// put all elements in arraylist al, al.get(i)));
ArrayList<Integer> al = new }
ArrayList(); System.out.println(hm);
for (int i = 0; i < a.length; }
i++) { }
al.add(a[i]);
}
Custom Sort Integer Inputs in TreeMap (Descending
Order)
import java.util.*; // Sample data
scores.put(85, "Vineet");
public class CustomSortTreeMap { scores.put(70, "Amit");
public static void main(String[] scores.put(92, "Sneha");
args) { scores.put(60, "Ravi");
// Create TreeMap with custom comparator to
sort in descending order
System.out.println("Sorted Student
TreeMap<Integer, String> scores
Scores (Descending):");
= new TreeMap<>(new
for (Map.Entry<Integer, String>
Comparator<Integer>() {
entry : scores.entrySet()) {
public int compare(Integer
a, Integer b) {
System.out.println(entry.getKey() + " → "
return b - a; //
+ entry.getValue());
Descending order
}
}
}
});
}
Key Features of Java