Implementing TreeMap | Techbirds
Hi all,
In this post I will discuss how we can use TreeMap. Map is one of the important part of collection framework in Java. TreeMap is direct Concrete Class that implements Map Interface.
A normal TreeMap with specified key and value pair.
import java.util.Collection; import java.util.TreeMap; import java.util.Iterator; public class TreeMapIterator { public static void main(String[] args) { // Create a TreeMap and populate it with elements TreeMap treeMap = new TreeMap(); treeMap.put(“key_1″,”element_1”); treeMap.put(“key_2″,”element_2”); treeMap.put(“key_3″,”element_3”); // Get a set of all the entries (key – value pairs) contained in the TreeMap Collection entrySet = treeMap.entrySet(); // Obtain an Iterator for the entries Set Iterator it = entrySet.iterator(); // Iterate through TreeMap entries System.out.println(“TreeMap entries : “); while(it.hasNext()) System.out.println(it.next()); } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
import java.util.Collection; import java.util.TreeMap; import java.util.Iterator; public class TreeMapIterator { public static void main(String[] args) { // Create a TreeMap and populate it with elements TreeMap treeMap = new TreeMap(); treeMap.put(“key_1″,”element_1”); treeMap.put(“key_2″,”element_2”); treeMap.put(“key_3″,”element_3”); // Get a set of all the entries (key – value pairs) contained in the TreeMap Collection entrySet = treeMap.entrySet(); // Obtain an Iterator for the entries Set Iterator it = entrySet.iterator(); // Iterate through TreeMap entries System.out.println(“TreeMap entries : “); while(it.hasNext()) System.out.println(it.next()); } } |
486 total views, 2 views today
Share this On