Tuesday, 29 March 2016

TreeMap operations


Check if a value exists in Treemap
TreeMap treeMap = new TreeMap();
treeMap.put("1", "One");
treeMap.put("2", "Two");
treeMap.put("3", "Three");
System.out.println(treeMap.containsValue("Three"));

// Get lowest and highest key stored
System.out.println("Lowest key: " + treeMap.firstKey());
System.out.println("Highest key: " + treeMap.lastKey());


Get keys and values from TreeMap
Set set = treeMap.entrySet();
for (Map.Entry entry : set) {
     System.out.print(entry.getKey() + " : " + entry.getValue());
}


Get Synchronized Map
Map map = Collections.synchronizedMap(treeMap);


Removing element from TreeMap
System.out.println("Size of TreeMap after addition : " 
                     + treeMap.size());
treeMap.remove("2");
System.out.println("Size of TreeMap after removal : " 
                     + treeMap.size());

No comments:

Post a Comment

Note: only a member of this blog may post a comment.