Map Collection in Java

Java Map, maps unique keys to values. A map cannot contain duplicate keys; each key can map to at most one value. For example, Starbucks. When you order something, you give them your name for them to know to whom the order belongs, right? Now let’s imagine you need to model the same thing in Java. For convenience, let’s assume you have two classes for the case: Customer and Order. This is when the Map collection comes in handy. The waiter needs a way to relate each Order to each Customer, so you can use a map to model that.

As discussed in the Java Collections Framework, the java.util.Map interface represents a mapping between a key and a value. The Java Map is an interface and it is not a subtype of the Collection interface and you need to instantiate a concrete implementation of the interface in order to use it. Therefore it behaves a bit different from the rest of the collection types.

There is a confusion regarding Map, “whether it is a part of Collections Framework or not?”

Map is an interface which does not extents the Collection interface so it is not a true collection.  However, these interfaces contain collection-view operations, which enable them to be manipulated as collections. Hence, studying under Java Collections Framework.

There are several implementation of Map Interface, but we will include only 4 concrete class in this tutorial which are most common – they are HashMap, Hashtable, LinkedHashMap, and TreeMap. Let’s see the characteristics and behaviors of each implementation.

Concrete Class/Map Interface Duplicate Elements Ordered Sorted
HashMap Map Unique keys No Order No
Hashtable Map Unique keys No Order No
LinkedHashMap Map Unique keys By Insertion Order or Last Accessed No
TreeMap SortedMap Unique keys Key Order Natural/Custom

HashMap Class

  • Implements Map and extends AbstractMap
  • Provides unsorted and unordered Map
  • It allows one null key and numerous null values
  • HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls

LinkedHashMap Class

  • Extends HashMap and implements Map interface
  • Maintains a linked list of elements within Map in the order in which they are inserted
  • Elements are stored or removed slowly in comparison to HashMap
  • Iteration is faster

Hashtable Class

  • Similar to Vector, Hashtable also provides synchronized operations
  • Does not allow null key or a null value
  • For storing and retrieving objects of a Hashtable, the objects that are used as keys must implement the hashCode() and equals() methods

TreeMap Class

  • Maintains data in sorted order by unique key and pair values
  • Sorts the elements in ascending order

 

Java Map Methods:

  • boolean containsKey(Object k) : It is used to search the specified key from this map.

Example:

if (mapHttpErrors.containsKey("200")) {

    System.out.println("Http status 200");

}
  • void clear( ) : Removes all key/value pairs from the invoking map.

Example:

mapHttpErrors.clear();

System.out.println("Is map empty? " + mapHttpErrors.isEmpty());
  • boolean containsValue(Object v) : Returns true if the map contains v as a value. Otherwise, returns false.

Example:

if (mapHttpErrors.containsValue("OK")) {

    System.out.println("Found status OK");

}
  • Set entrySet( ) : It is used to return the Set view containing all the keys and values.

Example:

Set<Map.Entry<String, String>> entries = mapCountryCodes.entrySet();

for (Map.Entry<String, String> entry : entries) {

    String code = entry.getKey();

    String country = entry.getValue();
  • Object get(Object k) : It is used to return the value for the specified key.

Example:

String status301 = mapHttpErrors.get(301);

System.out.println("301: " + status301);
  • int hashCode( ) : Returns the hash code for the invoking map.

Example:

public class Employee {
    protected long   employeeId;
    protected String firstName;
    protected String lastName;

public int hashCode(){
    return (int) employeeId *
               firstName.hashCode() *
                lastName.hashCode();
  }
}
  • boolean isEmpty( ) : Returns true if the invoking map is empty. Otherwise, returns false.

Example:

if (mapHttpErrors.isEmpty()) {

    System.out.println("No Error");

} else {

    System.out.println("Have HTTP Errors");

}
  • Set keySet( ) : It is used to return the Set view containing all the keys.

Example:

Map<String, String> mapCountryCodes = new HashMap<>();

mapCountryCodes.put("1", "USA");

mapCountryCodes.put("44", "United Kingdom");

mapCountryCodes.put("33", "India");

mapCountryCodes.put("81", "China");

Set<String> setCodes = mapCountryCodes.keySet();

Iterator<String> iterator = setCodes.iterator();

while (iterator.hasNext()) {

   String code = iterator.next();

    String country = mapCountryCodes.get(code);

    System.out.println(code + " => " + country);

}
  • void putAll(Map m) : It is used to insert the specified map in this map.

Example:

Map<String, String> mapLang = new TreeMap<>();

mapLang.put(".c", "C");

mapLang.put(".java", "Java");

mapLang.put(".pl", "Perl");

mapLang.put(".cs", "C#");

mapLang.put(".php", "PHP");

System.out.println(mapLang);
  • Object remove(Object k) : It is used to delete an entry for the specified key.

Example:

String removedValue = mapHttpErrors.remove(500);

if (removedValue != null) {
    System.out.println("Removed value: " + removedValue);
}
  • int size( ) : Returns the number of key/value pairs in the map.

Example:

int size = mapHttpErrors.size();
  • Collection values( ) : Returns a collection containing the values in the map.

Example:

Collection<String> countries = mapCountryCodes.values();
for (String country : countries) {
    System.out.println(country);
}

 

Find the working example on p3lang Github repo.

 

 

 

 

References:

https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html

%d bloggers like this: