A TreeMap is a category in Map interface. To implement this in java, an interface “NavigableMap” is used. It also stores the key, value pair in a natural order or any specified order.
TreeMap has some specific features are listed below….
- · It accept only null values,not the null keys.
- · The ordering of entries may be in natural order or any order provided by the comparator.
- · It follows Red-Black Tree for internal implementation.
How to implement TreeMap in java?
- It includes builtin packages in java(java.util.Map,java.util.TreeMap).
- A public class TreeMapEg is created with main function().
- An object instance is created for TreeMap.
- To add the key, value pair, a builtin function put() is used.
- Get() function is used to find the given key in the treeMap and gives you the key value pair.
- containsKey() checks the key in the treeMap.
- getValue(),getKey() is used to get the value and key.
- Remove() is used to delete the key,value.
- Clear () clears all the values in treeMap.
- isEmpty() returns a Boolean value.
Program:
import java.util.Map;
import java.util.TreeMap;
public class TreeMapEg {
public static void
main(String[] args) {
// Let us
create a TreeMap
Map<String,
Integer> treeMap1 = new TreeMap<>();
//
inserting values for key-value pairs
treeMap1.put("Onion", 500);
treeMap1.put("Carrot", 200);
treeMap1.put("Brinjal", 300);
treeMap1.put("Tomato", 400);
treeMap1.put("Potato",350);
treeMap1.put("Cabbage",500);
// Search and
retrieve a key,value pair
System.out.println("Weight of the Tomato: " +
treeMap1.get("Tomato"));
// Check for a
key
if
(treeMap1.containsKey("Brinjal")) {
System.out.println("Brinjal is available.");
}
//Loop to
print the value,key pair
for
(Map.Entry<String, Integer> entry : treeMap1.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
treeMap1.remove("Cabbage");
System.out.println("Size of the TreeMap: " + treeMap1.size());
treeMap1.clear();
if(treeMap1.isEmpty())
System.out.println("The TreeMap is empty");
}
}
Output:
C:\raji\blog>javac TreeMapEg.java
C:\raji\blog>java TreeMapEg
Weight of the Tomato: 400
Brinjal is available.
The list of vegetables and its price:
Brinjal: 300
Cabbage: 500
Carrot: 200
Onion: 500
Potato: 350
Tomato: 400
Size of the TreeMap: 5
The TreeMap is empty
This is the simple way of implementing TreeMap in java. If you
have any queries, post in the comment.Keep
coding!!!!
No comments:
Post a Comment