|
|
Program: Basic TreeMap Operations.
Description: |
Below example shows basic operations on TreeMap like creating an object, adding key-value pair objects,
gtting value by passing key object, checking whether the map has elements or not, deleting specific entry, and size of the
TreeMap.
|
Code: |
package com.java2novice.treemap;
import java.util.TreeMap;
public class MyBasicOperations {
public static void main(String a[]){
TreeMap<String, String> hm = new TreeMap<String, String>();
//add key-value pair to TreeMap
hm.put("first", "FIRST INSERTED");
hm.put("second", "SECOND INSERTED");
hm.put("third","THIRD INSERTED");
System.out.println(hm);
//getting value for the given key from TreeMap
System.out.println("Value of second: "+hm.get("second"));
System.out.println("Is TreeMap empty? "+hm.isEmpty());
hm.remove("third");
System.out.println(hm);
System.out.println("Size of the TreeMap: "+hm.size());
}
}
|
|
Output: |
{first=FIRST INSERTED, second=SECOND INSERTED, third=THIRD INSERTED}
Value of second: SECOND INSERTED
Is TreeMap empty? false
{first=FIRST INSERTED, second=SECOND INSERTED}
Size of the TreeMap: 2
|
|
|
|
|
List Of All TreeMap Sample Programs:- Basic TreeMap Operations.
- How to iterate through TreeMap?
- How to copy Map content to another TreeMap?
- How to search a key in TreeMap?
- How to search a value in TreeMap?
- How to get all keys from TreeMap?
- How to get entry set from TreeMap?
- How to delete all elements from TreeMap?
- How to sort keys in TreeMap by using Comparator?
- How to sort keys in TreeMap by using Comparator with user define objects?
- How to get sorted sub-map from TreeMap?
- How to get first key element from TreeMap (Sorted Map)?
- How to get last key element from TreeMap (Sorted Map)?
- How to reverse sorted keys in a TreeMap?
|
|
|
When to use LinkedList or ArrayList?
Accessing elements are faster with ArrayList, because it is index based.
But accessing is difficult with LinkedList. It is slow access. This is
to access any element, you need to navigate through the elements one by
one. But insertion and deletion is much faster with LinkedList, because
if you know the node, just change the pointers before or after nodes.
Insertion and deletion is slow with ArrayList, this is because, during
these operations ArrayList need to adjust the indexes according to
deletion or insetion if you are performing on middle indexes. Means,
an ArrayList having 10 elements, if you are inserting at index 5, then
you need to shift the indexes above 5 to one more.
Do not confuse motion and progress. A rocking horse keeps moving but does not make any progress.
-- Alfred A. Montapert
|