Map Interface Tutorial in Java Collection

The Map Interface is part of the java collection framework. The Map interface in java collection uses Map as an object to map keys to values. In Map Interface eack key can have 1 value mapped to it and it does not support duplicate key value pair.

The Map Interface is implemented by below given Java Classes:

  • HashMap
  • TreeMap
  • LinkedHashMap

The Map Interface classifieds the methods into below given operations

Maps using JDK8 Aggregate Functions

The Map interface allows the use of aggregate functions from Java 8 (JDK 8) onwards

For instance , grouping student by subject using stream

// Group students by subject
Map<Subject, List<Student>> bySubject = students.stream()
.collect(Collectors.groupingBy(Student::getSubject));

Another of getting subject and total marks for each student

// Total marks in each subject by student
Map<Subject, Integer> bytotalMarks = students.stream()
.collect(Collectors.groupingBy(Student::getSubject,
Collectors.summingInt(Student::getTotalMarks)));

Methods of Map Interface

MethodDescription
V put(Object key, Object value)allows to insert an entry in the map
void putAll(Map map)allows to insert the given map in the map
V putIfAbsent(K key, V value)insert the given key and value if key does not exist in map
V remove(Object key)removes an entry for the given key
boolean remove(Object key, Object value)remove value associated to the key
Set keySet()returns the Set view with all keys
Set<Map.Entry<K,V>> entrySet()returns the Set view with all keys and values
void clear()reset the map
V compute(K key, BiFunction<? super K,? super V,? extends V> remappingFunction)allows to compute a mapping for the given key and value
V computeIfAbsent(K key, Function<? super K,? extends V> mappingFunction)allows to compute key value using the given function if key is null or not assigned yet
V computeIfPresent(K key, BiFunction<? super K,? super V,? extends V> remappingFunction)allows to compute if given key and value exists in map
boolean containsValue(Object value)returns true if given value exists in map
boolean containsKey(Object key)returns true if given key exists in map
boolean equals(Object o)compare the given Object with Map
void forEach(BiConsumer<? super K,? super V> action)executes the given action for each entry in the map until throws an exception.
V get(Object key)returns object that contains given key value
V getOrDefault(Object key, V defaultValue)returns the value to which the specified key is mapped
int hashCode()returns Map hash code value
boolean isEmpty()returns true if map is empty
V merge(K key, V value, BiFunction<? super V,? super V,? extends V> remappingFunction)associates the key with given value when key value is null or not assigned yet
V replace(K key, V value)replaces key value
boolean replace(K key, V oldValue, V newValue)replace given key’s old value with the new value
void replaceAll(BiFunction<? super K,? super V,? extends V> function)allows to replaces each entry’s value with the result of invoking the given function
Collection values()returns collection view of map values
int size()returns map size

Map Interface Example in Java Collection

package core.java.planforexams;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class BasicMapExample {
	public static void main(String[] args) {
        Map<Integer, String> names = new HashMap<Integer, String>();
        names.put(1, "Mohit Sharma");
        names.put(2, "Mihika Sharma");
        names.put(3, "Usha Sharma");
        System.out.println(" Names Map Size is :::" + names.size());
        // Convert Map to Set to enable traversing
        Set nameSet = names.entrySet(); 
        Iterator itr= nameSet.iterator();  
        while(itr.hasNext()){  
            // Convert back to Map for retrieving Key and Value
            Map.Entry nameEntry= (Map.Entry) itr.next();  
            System.out.println(nameEntry.getKey() + " " + nameEntry.getValue());  
        }  
    }
}
Output:
 Names Map Size is :::3
1 Mohit Sharma
2 Mihika Sharma
3 Usha Sharma

Leave a Reply

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

*