Loading

Map Overview

Indications/ Symbols:

  • <<       >>      : Interface
  • <          >       : Class
  • ---------->       : Implements

Key Points:

  • Map is a part of the collection framework which doesn't inherit the Collection Interface.
  • A map is a pre-defined Interface present in Java.util package and introduced from JDK1.2.
  • A map is a collection of key-value pairs. One key and value together is called an entry.
  • A key can be any type of object and value can be any type of object, but the key must be unique.
  • The value can be retrieved based on the key.

Map Interface

  • The Map Interface defines the standard operations of all types of map.
  • The implementation classes of Map Interface are:
  1. HashMap
  2. LinkedHashMap
  3. TreeMap
  4. Hashtable

Standard Methods of Map Interface

  1. public boolean put(object key, object value);
  2. public object get(object key);
  3. public boolean containsKey(object key);
  4. public boolean containsValue(object value);
  5. public boolean keySet();
  6. public int size();

Program to demonstrate HashMap working:

package com.quipoin;

import java.util.HashMap;

public class Demo {
	public static void main(String[] args) {
		HashMap hm=new HashMap<>();

		hm.put(10, "Java");
		hm.put("sql", 12);
		hm.put(5.6, 89);

		System.out.println(hm);
		System.out.println("------------------");
		
		//get() method is used to get the value based on the key specified.
		
		System.out.println(hm.get(10));      //Java
		System.out.println(hm.get(5.6));     //89
		System.out.println("------------------");
		
//containsKey() method is used to check if the specified key is present ornot.

		System.out.println(hm.containsKey(10));       //true
		System.out.println(hm.containsKey("SQL"));    //false
		System.out.println("------------------");

	//containsValue() method is used to check if the value is present or not
	
		System.out.println(hm.containsValue(12));       //true
		System.out.println(hm.containsValue("java"));   //false
		System.out.println("------------------");

		//size() method is used to find number of entries present in Map.
		
		System.out.println(hm.size());
		System.out.println("------------------");

		//keSet() method returns set of keys from the map;
		
		System.out.println(hm.keySet());
	}
}

Output:

{5.6=89, 10=Java, sql=12}
------------------
Java
89
------------------
true
false
------------------
true
false
------------------
3
------------------
[5.6, 10, sql]