Thursday 21 August 2014

Java Collections - Map

Map is an interface which is not derived from Collections interface as described in our previous post Java Collections. Map follows its own hierarchy .
It stores a key -value pair in which key should be unique and value can be anything related.
We use put method to store key-value pair in Map.

Can we Store Null key and value in Map?
Yes, we can store single null and corresponding null value in Map

Example of simple map :


import java.util.*;

public class MapDemo {

   public static void main(String[] args) {
      Map m1 = new HashMap(); 
      m1.put("Zara", "8");
      m1.put("Mahnaz", "31");
      m1.put("Ayan", "12");
      m1.put("Daisy", "14");
      System.out.println();
      System.out.println(" Map Elements");
      System.out.print("\t" + m1);
   }


Output : 

Map Elements
        {Mahnaz=31, Ayan=12, Daisy=14, Zara=8}

where Zara,Mahnaz ,Daisy ,Ayan are keya and corresponding are their values.

How to reverse a string in java
Implementations of Map:

There are three implementations of Map.
1.TreeMap
2.HashMap
3.Linked Hash Map

Order of map elements in iteration 

The order of the elements obtained from a Map depends on the type of Map they came from.

TreeMap
The elements are ordered by key.

HashMap
The elements will be in an unpredictable, "chaotic", order.

LinkedHashMap
The elements will be ordered by entry order or last reference order, depending on the type of LinkedHashMap.



Detailed description of Tree map:
present in Java.util.TreeMap class which is an implementation of Map.

Gives surety of sorting of elements.

Provides efficient means of adding key value pair and retrieving elements.

You might also like :

How to reverse a string in java



No comments:

Post a Comment