The SortedMap Interface

The SortedMap Interface


Posted in : Core Java Posted on : October 20, 2010 at 5:02 PM Comments : [ 0 ]

This section contains the detail about the SortedMap Interface in java.

The SortedMap Interface

The SortedMap Interface extends Maps. It maintains the elements in increasing order of key value.

Exception thrown by the methods :

Several methods throw a 'NoSuchElementException' when no items are in the invoking map. A 'ClassCastException' is thrown when an object is incompatible with the elements in a map. A 'NullPointerException' is thrown if an attempt is made to use a null object when null is not allowed in the map.

The methods of SortedMap are given below :

  Methods     Description  
Comparator comparator( ) Returns the invoking sorted map's comparator. If the
natural ordering is used for the invoking map, null is
returned.
Object firstKey( )  Returns the first key in the invoking map.
SortedMap headMap(Object end) Returns a sorted map for those map entries with keys
that are less than end.
Object lastKey( )  Returns the last key in the invoking map.
SortedMap subMap(Object start, Object end) Returns a map containing those entries with keys that
are greater than or equal to start and less than end
SortedMap tailMap(Object start)  Returns a map containing those entries with keys that
are greater than or equal to start.

Example :

The 'Map.Entry' interface enables you to work with a map entry. The 'entrySet( )' method declared by the Map interface returns a Set containing the map entries. Each of these set elements is a 'Map.Entry' object.


import java.util.*;

public class SortedMapDemo {
	
public static void main(String args[]) {
	// Create a hash map
	TreeMap tm = new TreeMap();
	// Put elements to the map
	tm.put("Nicole", new Double(3434.34));
	tm.put("Ketty", new Double(123.22));
	tm.put("Linsay", new Double(1378.00));
	tm.put("Jay Sean", new Double(99.22));
	tm.put("Sakira", new Double(-19.08));
	
	// Get a set of the entries
	Set set = tm.entrySet();
	// Get an iterator
	Iterator i = set.iterator();
	// Display elements
	while (i.hasNext()) {
		Map.Entry me = (Map.Entry) i.next();
		System.out.print(me.getKey() + ": ");
		System.out.println(me.getValue());
	}
	System.out.println();
	// Deposit 1000 into Nicole's account
	double balance = ((Double) tm.get("Nicole")).doubleValue();
	tm.put("Nicole", new Double(balance + 1000));
	System.out.println("Nicole's new balance: " + tm.get("Nicole"));
}

}

Output :

C:\Program Files\Java\jdk1.6.0_18\bin>java SortedMapDemo
 Jay Sean: 99.22
Ketty: 123.22
Linsay: 1378.0
Nicole: 3434.34
Sakira: -19.08

Nicole's new balance: 4434.34

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics