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

Comparable Example

Below is an example on how to use Comparable


import java.util.TreeSet;

class Item implements Comparable{

	private String name;
	private int quantity;

	public Item(String name, int quantity) {
		super();
		this.name = name;
		this.quantity = quantity;
	}

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

	public int getQuantity() {
		return quantity;
	}
	public void setQuantity(int quantity) {
		this.quantity = quantity;
	}

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

	public int compareTo(Item compareItem) {

		int compareQuantity = ((Item) compareItem).getQuantity();

		return this.quantity - compareQuantity;
	}
}

public class MyTreeSetComparable {

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

        Item it1 = new Item("Banana", 21);
        Item it2 = new Item("Orange", 2);
        Item it3 = new Item("Apple", 56);
        Item it4 = new Item("Sapota", 11);
        Item it5 = new Item("PIneapple", 6);

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

        System.out.println(ts);
    }
}

You may also like to read:
Comparator example
Difference between Comparator and Comparable interfaces

Comparator Example

Below is an example of Comparator

import java.util.Comparator;
import java.util.TreeSet;

public class MySetWithCompr {

    public static void main(String a[]){
    	MyComp obj = new MyComp();
        TreeSet<String> ts = new TreeSet<String>(obj);
        ts.add("RED");
        ts.add("ORANGE");
        ts.add("BLUE");
        ts.add("GREEN");
        ts.add("H");
        ts.add("AB");
        //Comparator cmp = ts.comparator();

        System.out.println(ts);
    }
}

//Comparator can be used for any type
//usage with String is given below
class MyComp implements Comparator<String>{

    public int compare(String str1, String str2) {
        //return str1.compareTo(str2);
    	//return str2.compareTo(str1);//sort in reverse order
    	//System.out.println("Hello from Comparator");
    	return (str1.length()-str2.length());
    }

}


You may also like to read:
Comparable Example
Difference between Comparator and Comparable

Similarity and Difference between Comparator and Comparable interfaces

Below are Similarity and Difference between Comparator and Comparable interfaces

Similarity:
#1.Both are interfaces
#2.Both are used for specifying sorting order of the objects stored in a Collection

Difference:
#1.Packages they are available
Comparator interface is defined in java.util package, but Comparable interface is defined in java.lang package

#2.Methods they declare
Comparator interface declares method
public int compare (Object obj1, Object obj2) which returns a -ve, zero, or +ve integer as the first argument is less than, equal to, or greater than second respectively.

But Comparable interface declares method public int compareTo(Object obj)

#3.How to implement?
The class(whose objects need to be sorted) need to implement Comparable, and provide body for compareTo(Object obj) method.

Not the actual class(whose objects need to be sorted), but another class need to implement Comparator. Need to be sent as parameter while creating Collection, or to Collections.sort() method.

#4.Using Comparable, objects can be sorted only on one criteria. Using Comparator, objects can be sorted based on different criteria.

You may also like to read:
Comparable Example
Comparator Example