Advertisement
TreeMap() |
---|
This constructor creates an empty TreeMap to hold a particular type of key-value pair objects. Example - |
TreeMap <String,Integer> tm = new TreeMap <String,Integer>();
Methods | Description |
---|---|
void clear() | Removes all the key/value pairs from the TreeMap. |
int size() | Returns the total number of key-value pairs in a TreeMap. |
boolean isEmpty() | Returns true if TreeMap has no key-value pair in it. |
V get(Object key) | Returns the value associated with a specified key. |
put(K key, V value) | Puts the specified key and its associated value in the TreeMap. |
K higherKey(K key) | Returns a key just greater than the specified key. |
K lowerKey(K key) | Returns a key just smaller than the specified key. |
Set<Map.Entry<K,V>> entrySet() | Returns the Set containing Map.Entry objects. |
//Java - Example of TreeMap
import java.util.*;
class TreeMapDemo
{
public static void main(String... ar)
{
TreeMap<String,Integer> tm = new TreeMap<String,Integer>();
tm.put("Tom", 14);
tm.put("Rick", 17);
tm.put("Ana", 15);
tm.put("Max", 20);
tm.put("Ian", 19);
System.out.println("TreeMap contents in an ascending order of its keys-" +tm);
System.out.println("Value at the key Ian is "+ tm.get("Ian"));
System.out.println("Value at the key Max is "+ tm.get("Max"));
System.out.println("Key greater than Ana is ")+ tm.higherKey("Ana");
System.out.println("Key smaller than Rick is ")+ tm.lowerKey("Rick");
}
}
TreeMap contents in an ascending order of its keys-{Ana=15, Ian=19, Max=20 Rick=17, Tom=14}
Value at the key Ian is 19
Value at the key Max is 20
Key greater than Ana is Ian
Key smaller than Rick is Max
Advertisement
//Java - Iterating over entries in a TreeMap by using the entrySet() method
import java.util.*;
class TreeMapDemo
{
public static void main(String... ar)
{
TreeMap<String,Integer> tm = new TreeMap<String,Integer>();
tm.put("Tom", 14);
tm.put("Rick", 17);
tm.put("Ana", 15);
tm.put("Max", 20);
tm.put("Ian", 19);
System.out.println("Iterating TreeMap using Map.Entry and for-each loop");
Set<Map.Entry<String,Integer>> set = tm.entrySet();
for(Map.Entry <String,Integer> me : set)
{
System.out.print(getKey() +":");
System.out.println(getValue());
}
}
}
{Ana=15, Ian=19, Max=20 Rick=17, Tom=14}
Iterating TreeMap using Map.Entry and for-each loop
Ana:15
Ian:19
Max:20
Rick:17
Tom:14
Advertisement
Advertisement
Please check our latest addition
C#, PYTHON and DJANGO
Advertisement