Map


Map

A map consists of values based on the key and value pair. Every key and value pair is known as an entry. It contains unique keys. When we have to search, update or delete elements on the basis of a key then a map can be used. The following are the two interfaces for implementing Map in java: Map and SortedMap and the three classes used are: HashMap, LinkedHashMap, and TreeMap. It cannot have duplicate keys but can have duplicate values.

HashMap - It doesn’t have any order.

LinkedHashMap – It has insertion order.

TreeMap - It has ascending order.

Various methods of map interface are as follows:

  • Set keySet() – Used to return the set view containing all keys
  • V Remove(Object key) – Used to remove entry for the specified key
  • void clear() – Used to reset the map
  • int hashCode – Used to return hash code value for the map
  • V get(Object key) – Used to return the object that contains the value associated with the key
  • boolean isEmpty() – Used to check if map is empty or not
  • boolean isEmpty() – Used to check if map is empty or not
  • int size() – Used to return number of entries in map
  • V replace(K key, V value) – Used to replace value for the mentioned key
  • Collection values() – Used to return collection view of the values present in the map
  • void putAll(Map map) – used to insert mentioned map in the map

Example:

Com.knowledge2life import java.util.*; public class Main { public static void main(String[] args) { Map map=new HashMap(); map.put(1,"Knowledge2life"); map.put(5,"Knowledge2life"); map.put(2,"Knowledge2life"); Set set=map.entrySet(); Iterator itr=set.iterator(); while(itr.hasNext()){ Map.Entry entry=(Map.Entry)itr.next(); System.out.println(entry.getKey()+" "+entry.getValue()); } } }

OUTPUT:

1 Knowledge2life
2 Knowledge2life
5 Knowledge2life