|
|
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?
|
|
|
What is race condition?
A race condition is a situation in which two or more threads or
processes are reading or writing some shared data, and the final
result depends on the timing of how the threads are scheduled.
Race conditions can lead to unpredictable results and subtle
program bugs. A thread can prevent this from happening by locking
an object. When an object is locked by one thread and another
thread tries to call a synchronized method on the same object,
the second thread will block until the object is unlocked.
Do not confuse motion and progress. A rocking horse keeps moving but does not make any progress.
-- Alfred A. Montapert
|