Archives: Map

Java – Synchronized HashMap Example

HashMap is a non-synchronized collection class. If we need to perform thread-safe operations on it then we must need to synchronize it explicitly.

Iterator should be used in a synchronized block even if we have synchronized the HashMap explicitly.


Java – Map Iterate Example

[code lang=”java”]import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class LoopMap {

public static void main(String[] args) {

// initial a Map
Map<String, String> map = new HashMap<String, String>();
map.put("1", "Jan");
map.put("2", "Feb");
map.put("3", "Mar");
map.put("4", "Apr");
map.put("5", "May");
map.put("6", "Jun");

System.out.println("Example 1…");
// Map -< Set -> Iterator -< Map.Entry -> troublesome
Iterator iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry mapEntry = (Map.Entry) iterator.next();
System.out.println("The key is: " + mapEntry.getKey() + ",value is :" + mapEntry.getValue());
}

System.out.println("Example 2…");
// more elegant way
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
}

System.out.println("Example 3…");
// weired way, but work anyway
for (Object key : map.keySet()) {
System.out.println("Key : " + key.toString() + " Value : " + map.get(key));
}

}

}[/code]


Java – NavigableSet Example

[code lang=”java”]import java.util.Arrays;
import java.util.Iterator;
import java.util.NavigableSet;
import java.util.TreeSet;

public class NavigableSetDemo {

public static void main(String[] args) {

NavigableSet<String> navigableSet = new TreeSet<String>(Arrays.asList("X", "B", "A", "Z", "T"));

Iterator<String> iterator = navigableSet.descendingIterator();

System.out.println("Original Set :");
while (iterator.hasNext()) {
System.out.println(iterator.next());
}

iterator = navigableSet.iterator();

System.out.println("Sorted Navigable Set :");

while (iterator.hasNext()) {
System.out.println(iterator.next());
}

System.out.printf("Head Set : %s.%n", navigableSet.headSet("X"));

System.out.printf("Tail Set : %s.%n", navigableSet.tailSet("T", false));

System.out.printf("Sub Set : %s.%n", navigableSet.subSet("B", true, "X", true));

System.out.printf("Last Element : %s%n", navigableSet.last());

System.out.printf("First Element : %s%n", navigableSet.first());

System.out.printf("Reverse Set : %s%n", navigableSet.descendingSet());

System.out.printf("Original Set : %s%n", navigableSet);

}

}[/code]
Output:

Original Set :
Z
X
T
B
A
Sorted Navigable Set :
A
B
T
X
Z
Head Set : [A, B, T].
Tail Set : [X, Z].
Sub Set : [B, T, X].
Last Element : Z
First Element : A
Reverse Set : [Z, X, T, B, A]
Original Set : [A, B, T, X, Z]