Professional Documents
Culture Documents
tm1.put(3, "Welcome");
tm1.put(2, "All");
tm1.put(1, "Hello");
System.out.println(tm1);
System.out.println(tm2);
tm1.put(3, "Welcome");
tm1.put(2, "All");
tm1.put(1, "Hello");
System.out.println(tm1); // output :- {1=Hello, 2=All, 3=Welcome}
tm1.put(2,”Everyone”);
System.out.println(tm1); // output :- {1=Hello, 2=Everyone, 3=Welcome}
3. Removing Element: In order to remove an element from the
TreeMap, we can use the remove() method. This method takes the key
value and removes the mapping for the key from this treemap if it is
present in the map.
tm1.remove(3);
import java.util.Map;
import java.util.HashMap;
import java.util.TreeMap;
public class HashMapVsTreeMapExample
{
public static void main(String args[])
{
/*------------HashMap implementation----------------*/
Map<Integer, String> hm=new HashMap<Integer, String>();
//adding elements to the HashMap
hm.put(9, "Red");
hm.put(12, "Black");
hm.put(6, "Green");
hm.put(19, "White");
System.out.println("HashMap iteration Order:");
//iteration over map using for each loop
for(Map.Entry<Integer, String>entry: hm.entrySet())
{
//getting keys and values using method
System.out.println(entry.getKey() + " = " +entry.getValue());
}
/*------------TreeMap implementation----------------*/
Map<Integer, String> tm=new TreeMap<Integer, String>();
//adding elements to the TreeMap
tm.put(9, "Red");
tm.put(12, "Black");
tm.put(6, "Green");
tm.put(19, "White");
System.out.println("TreeMap iteration Order:");
//iteration over map using for each loop
for(Map.Entry<Integer, String>entry: tm.entrySet())
{
//getting keys and values using method
//prints list in sorted order
System.out.println(entry.getKey() + " = " +entry.getValue());
}
}
}