Java – SortedMap Example

SortedMap interface is part of java.util package. SortedMap interface can add key and value put(key, value) pair elements. This SortedMap permits null value. Key and value of SortedMap can get by Set Interface and Map interface through Iterator interface.

SortedMap example give a method, how to use SortedMap in java.

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

public class SortedMapExample {

    public static void main(String[] args) {

        SortedMap<Integer,String> sm=new TreeMap<Integer, String>();

        sm.put(new Integer(2), "Two");
        sm.put(new Integer(1), "One");
        sm.put(new Integer(4), "Four");
        sm.put(new Integer(3), "Three");
        sm.put(new Integer(5), "Five");

        Set s=sm.entrySet();

        // Using iterator in SortedMap 
        Iterator i=s.iterator();

        while(i.hasNext())
        {
            Map.Entry m =(Map.Entry)i.next();

            int key = (Integer)m.getKey();
            String value=(String)m.getValue();

            System.out.println("Key :"+key+"  value :"+value);
        }
    }
}

Output

Key :1 value :One
Key :2 value :Two
Key :3 value :Three
Key :4 value :Four
Key :5 value :Five

Tags:

Bookmark  

 

One Response to “Java – SortedMap Example”

  1. suffiyan says:

    This is not compiling plz give sorted map Example i m not getting it?

Leave a Reply

Security Code:

 

  Random Post