Java Map, HashMap and TreeMap

A Map is one of the Collection, and Map is an interface extended from Collection interface. Collection is Base interface of all Java Collection.

As briefed in , List and Set based Collection is used to store and retrieve individual elements. But Map is used to store Key and Value pair object. Key and Value can be any objects.

Map has two different implementations HashMap and TreeMap. In HashMap, Keys are stored based on Hashing technique, where as in TreeMap, Keys are stored in ascending order. However order can be changed by using Comparator or Comparable interfaces.

Below is simple example of TreeMap, which uses default natural ordering on keys, to store elements.

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

public class HashMapDemo {

public static void main(String[] args) {

//Map is used to store key:value pairs

HashMap hm = new HashMap();
hm.put("sfdsfds"/*key*/, "nfghgfhfg"/*value*/);
hm.put("qwdfdsfs", "nfghgfhgf");
hm.put("wererwe", "mhjuytuy");
hm.put("qwewewq", "vnfkhfjfk");
hm.put("nvcsdsfh", "wyetrwye");
hm.put("mnxcvbcjx", "werewhwej");
hm.put("msdfksdfhsd", null);

System.out.println("Value of key,wererwe:"+hm.get("wererwe"));

Set s= hm.entrySet();

//Now s is Set having all the Entry

Iterator itr1 = s.iterator();
while(itr1.hasNext())
{
Map.Entry me = (Map.Entry)itr1.next();
System.out.println("Key:"+me.getKey()+" "+"value:"+me.getValue());
}
return;
}
}

Below is TreeMap example, which uses Comparator, to control the order of elements stored.

Steps to change sorting order of TreeMap

1. Write a class, implementing from Comparator interface
2. In above class, implement the method public int compare(), with the comparison logic, return positive, negative or zero accordingly, from the compare() method.
3. When creating object of TreeMap, pass object of class(created in step 1) to constructor of TreeMap.Now whenever you add an element to TreeMap your comparison logic is used, instead of default natural ordering logic.

Using Comparator with TreeMap example

import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

//Step 1
class MyComp1 implements Comparator{

//Step 2
public int compare(String str1, String str2) {
    //return str1.compareTo(str2);
    //return str2.compareTo(str1);
    return str1.length()-str2.length();
    }
 }

public class MyTreeMapComparator {
  public static void main(String a[]){
    //the treemap sorts by key
    //Step 3
    TreeMap hm = new TreeMap(new MyComp1());
    //add key-value pair to TreeMap
    hm.put("java", "language");
    hm.put("computer", "machine");
    hm.put("india","country");
    hm.put("mango","fruit");
    hm.put("ajfdshfsf","ksjfhgikure");
    hm.put("rtrjbsjdff", "bvdsufusfs");
    hm.put("gh", "fsfsdfsd");
    hm.put("k", "arg1");
    //System.out.println(hm);

    Set s= hm.entrySet();
	Iterator itr1 = s.iterator();
	while(itr1.hasNext())
	{
	Map.Entry me = (Map.Entry)itr1.next();
	System.out.println("Key:"+me.getKey()+" "+"value:"+me.getValue());
	}
    }
}

TreeMap with Comparable

import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;

class MyItem implements Comparable{

	private String name;
	private int numbers;

	public MyItem(String name, int numbers) {
	super();
	this.name = name;
	this.numbers = numbers;
	}

	public String getName() {
	return name;
	}
	public void setName(String name) {
	this.name = name;
	}

	public int getnumbers() {
	return numbers;
	}
	public void setnumbers(int numbers) {
	this.numbers = numbers;
	}

	public String toString()
	{
	return " "+name+" "+numbers;
	}

	public int compareTo(MyItem compareItem) {
	int comparenumbers = ((MyItem) compareItem).getnumbers();
	return this.numbers - comparenumbers;
	}
}

public class MyTreeMapComparable {

    public static void main(String a[]){
        TreeSet ts = new TreeSet();

        MyItem it1 = new MyItem("Bread", 52);
        MyItem it2 = new MyItem("Tomato", 31);
        MyItem it3 = new MyItem("Apple", 61);
        MyItem it4 = new MyItem("Sapota", 12);
        MyItem it5 = new MyItem("Pumpkin", 16);

        ts.add(it1);
        ts.add(it2);
        ts.add(it3);
        ts.add(it4);
        ts.add(it5);

        System.out.println(ts);
    }
}

Also note that java.lang.Comparable can as well be used with TreeMap, to take control over sorting order of elements. However, limitations of Comparable interface, will apply here as well.
You may also like to read:
Comparator with TreeSet
Comparator and Comparable differences
How to write Generic class