Section 4
Learning Objectives: In this lesson, we will learn about the Java Map interfaces and its various operations and methods. By the end of this lesson, learners will be able to:
Explain the Map<K,V> Interface.
Describe HashMap and TreeMap.
Demonstrate how to use Map interface, TreeMap Class, and HashMap class.
Describe the difference between a TreeMap and a HashMap.
Section 4
Map<K,V> interface
Table of Contents
Topic 1: Map<K,V> Interface
Topic 2: Classes that implement Map<K,V> Interface
Topic 3: Common Methods of Map<K,V>
Topic 4: Overview of HashMap<K,V>
Topic 5: HashMap Constructors
Topic 6: Declare and Initialize a HashMap<K,V>
Topic 7: Common Methods of HashMap<K,V>
Example: HashMap<K,V>
Example: Access HashMap Elements
Example: Iterate through a HashMap
Topic 8: Overview of TreeMap<K,V> class
Topic 9: TreeMap<K,V> Constructors
Topic 10: Declare and initialize a TreeMap<K,V>
Topic 11: Common Methods of TreeMap<K,V>
Example - TreeMap<K,V>
Example: Access TreeMap Element
LAB - 303.7.6 - HashMap and TreeMap Processing
LAB - 303.7.7 - Phone Directory using TreeMap
Practice Assignment #303.7.2
Topic 1: Map<K,V> Interface
Keys are unique values associated with single values. A map cannot contain duplicate keys. In Java, elements of Map<K,Y> are stored in key/value pairs. Map<K,Y> → You might recall this syntax from multiple type parameters in generic.
The Key type should not be mutable.
The Key type should be comparable: Enums, integer types, and String are the most common Key types.
Floating-point keys should be avoided.
Each key maps to one value, at most.
Now, we can access those values using their corresponding keys.
If you need multiple values for a given Key, consider Map<K, ArrayList<V>>.
Topic 2: Classes That Implement Map<K,V> Interface
Map<E,V> is an interface. We cannot provide the direct implementation of it because we cannot create objects from it. In order to use functionalities of the Map<E,V> interface, the Java Collections Framework (JCF) provides the following class for implementations of Map<K,V> interface.
All are based on the AbstractMap<K,V> base class:
EnumMap - If your Key type is an enum, this is the most efficient map to use.
HashMap - This is a hash-table based implementation.
TreeMap - This is a sorted map based on a red-black tree.
Topic 3: Common Methods of Map<K,V>
The most commonly used Map methods:
keySet() - Returns the Set<K> of all keys in the map.
remove(K key) - Removes the key and its associated value from the map.
replace(K key, V value) - Replaces the entry for the given key.
clear() - Removes all mappings.
containsKey(K key) - Tests whether the map includes the given key.
containsValue(V v) - Tests whether the map includes the given value.
get(K key) - Gets the value associated with the given key.
put(K key, V value) - Associates value with the given key.
Topic 4: Overview of HashMap<K,V>
HashMap<K,V> class implements the Map<K,V> interface.
HashMap<K,V> utilizes a hash table for its backing store.
HashMap has NO natural ordering.
HashMap can have one null key.
HashMap can have any number of null values.
We cannot store duplicate keys in HashMap. However, if you try to store a duplicate key with another value, it will replace the value.
HashMap provides NO guarantee around the ordering of its elements.
The default capacity for a HashMap is 16.
Topic 5: HashMap Constructors
HashMap has four constructors:
HashMap() - Creates a map with default capacity and load factor.
HashMap(Map<? extends K, ? extends V>) - Creates a copy of the given map.
HashMap(int initialCapacity) - Use this constructor if you know how many elements the map will contain.
HashMap(int initialCapacity, float loadFactor) - The loadFactor affects how often the map is re-hashed.
Topic 6: Declare and Initialize a HashMap<K,V>
When you declare and initialize a HashMap<K,V>, you should specify data type for type parameter: Example:
HashMap<Integer, String> hpObj = new HashMap<Integer, String>();
HashMap<String, Integer> hpObj2 = new HashMap<tring, Integer>();
HashMap<Integer, Integer> hpObj3 = new HashMap<Integer, Integer>();
HashMap<Integer, Float> hpObj4 = new HashMap<Integer, Float>();
HashMap<Integer, UserDefineObject> hpObj5 = new HashMap<>(); In order to create a tree set, we must import the java.util.HashMap package on top of the class.
HashMap<datatypeOfkey, dataytpeOfValue> name_of_hashMap =new HashMap<datatypeOfkey, dataytpeOfValue> ();
Topic 7: Common Methods of HashMap<K,V>
void clear()
Object clone()
boolean containsKey(Object key)
boolean containsValue(Object Value)
Value get(Object key)
boolean isEmpty()
Value remove(Object key)
void putAll(Map m)
Set keySet()
value put(Key k, Value v)
int size()
Collection values()
Example: HashMap<K,V>
As you can see, all of the duplicate values are present in the output, and Key is not repeated. The Value of Key 1 and 3 is replaced with new values.
If you try to add a null key, you will get an error.
Elements are sorted in ascending order by Key
Example: Access HashMap Elements
The methods that we used in our code include:
entrySet() - returns a set of all the key/values mapping (entry) of a hashmap.
keySet() - returns a set of all the keys of a hashmap.
values() - returns a set of all the maps of a hashmap.
get() - retrieves the value mapped by the specified key, or null if the hashmap contains no mapping for the key.
Output:
Example: Iterate Through a HashMap
In this example, we will demonstrate, how to iterate through each entry of the hashmap. We can use enhanced loop. We can iterate through keys only, values only, and key/value mapping.
Topic 8: Overview of TreeMap<K,V> Class
The TreeMap class implements Map<K,V> interface
The TreeMap class provides the tree data structure.
Duplicate keys are not possible; it allows only Unique keys.
It cannot have a null key, but can have multiple null values.
It stores the keys in a sorted order or by a comparator provided at map creation time.
The main difference between them is that HashMap is an unordered collection, while TreeMap is sorted in the ascending order of its keys.
Topic 9: TreeMap<K,V> Constructors
The TreeMap has four constructors:
TreeMap() - constructs a TreeMap using the natural ordering of the Keys.
TreeMap(Comparator<K> comparator) - constructs a TreeMap using a custom comparison.
TreeMap(Map<? extends K,? extends V> m) - creates a copy of an existing map.
TreeMap(SortedMap<K,? extends V> m) - creates a copy of an existing map.
Topic 10: Declare and Initialize a TreeMap<K,V>
When you declare and initialize a TreeMap<K,V>, you should specify data type for type parameter: Example:
TreeMap<Integer, String> hpObj = new TreeMap<Integer, String>();
TreeMap<String, Integer> hpObj2 = new TreeMap<tring, Integer>();
TreeMap<Integer, Integer> hpObj3 = new TreeMap<Integer, Integer>();
TreeMap<Integer, Float> hpObj4 = new TreeMap<Integer, Float>();
TreeMap<Integer, UserDefineObject> hpObj5 = new TreeMap<UserDefineObject>(); In order to create a tree set, we must import the java.util.TreeMap package on top of the class.
TreeMap<datatypeOfkey, dataytpeOfValue> name_of_hashMap =new TreeMap<datatypeOfkey, dataytpeOfValue> ();
Topic 11: Common Methods of TreeMap<K,V>
entrySet() - returns a set of all of the key/values mapping (entry) of a treemap.
keySet() - returns a set of all of the keys of a treemap.
values() - returns a set of all of the maps of a treemap.
void size() - returns the number of key-value pairs present in the treemap.
void isEmpty() - returns true if the treemap contains no key-value mappings.
boolean containsKey (Object key) - returns true if a specified key is present in the treemap.
boolean containsValue (Object key) - returns true if a specified value is mapped to at least one key in the treemap.
get (Object key) - retrieves the value mapped by the specified key, or null if the treemap contains no mapping for the key.
Object remove (Object key) - removes the key-value pair for the specified key from the treemap if present.
Comparator comparator() - returns the comparator used to order the keys in this treemap, or null if this map uses the natural ordering of its keys.
Object firstKey() - returns the first (least) key currently in the treemap.
Object lastKey() - returns the last (greatest) key currently in the treemap.
higherKey(Object key) - returns the least key strictly greater than the specified key.
NavigableMap descendingMap() - returns a reverse order view of the mappings contained in the treemap.
Example - TreeMap<K,V>
In this example, we will demonstrate:
How to create a TreeMap.
How to add elements to TreeMap using put() method.
How to add duplicate Key and value.
How to add null key and value.
As you can see, all of the duplicate values are present in the output, and Key is not repeated. The Value of Key 1 and 3 is replaced with new value.
If you try to add a null key, you will get an error.
Elements are sorted in ascending order by Key.
Access HashMap Elements
In this example, we will demonstrate:
How to use the get() method to access the value from the hashmap.
How to use keySet(), values(), and entrySet() - we can also access the keys, values, and key/value pairs of the hashmap as set views.
Iterate Through a HashMap
In this example, we will demonstrate, how to iterate through each entry of the hashmap. We can use enhanced loop. We can iterate through keys only, values only, and key/value mapping.
Overview of TreeMap<K,V> Class
TreeMap class is similar to HashMap class. The main difference between them is that HashMap is an unordered collection, while TreeMap is sorted in the ascending order of its keys.
TreeMap<K,V> Constructors
The TreeMap has four constructors:
TreeMap(); constructs a TreeMap using the natural ordering of the Keys.
TreeMap(Comparator<K> comparator); constructs a TreeMap using a custom comparison.
TreeMap(Map<? extends K,? extends V> m); creates a copy of an existing map.
TreeMap(SortedMap<K,? extends V> m); creates a copy of an existing map.
Declare and Initialize a TreeMap<K,V>
When you declare and initialize a TreeMap<K,V>, you should specify data type for type parameter: Example:
Common Methods of TreeMap<K,V>
entrySet() - returns a set of all of the key/values mapping (entry) of a treemap.
keySet() - returns a set of all of the keys of a treemap.
values() - returns a set of all of the maps of a treemap.
void size() - returns the number of key-value pairs present in the treemap.
void isEmpty() - returns true if the treemap contains no key-value mappings.
boolean containsKey (Object key) - returns true if a specified key is present in the treemap.
boolean containsValue (Object key) - returns true if a specified value is mapped to at least one key in the treemap.
get (Object key) - retrieves the value mapped by the specified key, or null if the treemap contains no mapping for the key.
Object remove (Object key): removes the key-value pair for the specified key from the treemap if present.
Comparator comparator(): returns the comparator used to order the keys in this treemap, or null if this map uses the natural ordering of its keys.
Object firstKey(): returns the first (least) key currently in the treemap.
Object lastKey(): returns the last (greatest) key currently in the treemap.
higherKey(Object key): returns the least key strictly greater than the specified key.
NavigableMap descendingMap(): returns a reverse order view of the mappings contained in the treemap.
TreeMap<K,V>
In this example, we will demonstrate:
How to use the get() method to access the value from the hashmap.
How to use keySet(), values(), and entrySet() - we can also access the keys, values, and key/value pairs of the hashmap as set views.
Map Comparisons
Property | HashMap | TreeMap |
---|---|---|
Time Complexity of get, put, remove and containsKey | O(1) | O(log N) |
Iteration Order | Unordered | Natural order of keys, or by customer comparator. |
Null Key | 1 allowed | Not allowed for natural order. |
Interfaces | Map | Map, SortedMap, NavigableMap. |
Storage | Array of linked-list buckets. | Red-black, self-balancing tree. |
Key Requirements | Equals and hashCode methods are required. | Equals and hashCode methods are required, unless a custom Comparator is provided. |
Applications | General purpose and fast. | Useful where Key ordering is important. |
Hands-On Lab
Find the below Labs on Canvas under the Assignment section.
GLAB - 303.11.6 - HashMap and TreeMap Processing
GLAB - 303.11.7 - Phone Directory using TreeMap
Practice Assignment
Find the assignment PA 303.11.1 - Practice Assignment - Java Collection on Canvas under Assignment section.
Knowledge Check
What is a Map?
What are Core Classes Implementing Map Interface?
What is the difference between Set and List?
When would you use use HashMap and TreeMap?
Summary
The Collection framework represents a unified architecture for storing and manipulating a group of objects. It has interfaces, implementations (e.g., classes), and algorithms.
Java Collections can achieve all of the operations that you perform on data such as searching, sorting, inserting, manipulating, and deleting.
java.util packages contain the primary collection classes and interfaces.
The list interface inherits the collection interface. List interface contains the data structures that are used to store ordered data or collection of objects.
ArrayList is the simplest implementation of the List interface.
LinkedList collection internally uses a doubly linked list mechanism for storing elements.
The set interface is a part of the java.util package and extends from the collection interface. Set is a structure that does not allow the collection to have duplicate values or more than one null value.
The HashSet collection that implements the Set interface has distinct values stored in it.
References
Last updated