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.

Map map = Collections.synchronizedMap(new HashMap());
...
// This doesn't need to be in synchronized block
Set set = map.keySet();
// Synchronizing on map, not on set
synchronized (map) {
    // Iterator must be in synchronized block
    Iterator iterator = set.iterator();
    while (iterator.hasNext()) {
        ...
    }
}

Java – Convert Set to List

import java.util.*;

public class SetToList {
public static void main(String[] args) {
//
// Create a Set and add some objects into the Set.
//
Set<Object> set = new HashSet<Object>();
set.add("A");
set.add(new Long(10));
set.add(new Date());

//
// Convert the Set to a List can be done by passing the Set instance into
// the constructor of a List implementation class such as ArrayList.
//
List<Object> list = new ArrayList<Object>(set);
for (int i = 0; i < list.size(); i++) {
Object o = list.get(i);
System.out.println("Object = " + o);
}
}
}

Java – Convert Array to Set

import java.util.*;

public class ArrayToSetExample {
public static void main(String[] args) {
Integer[] numbers = {7, 7, 8, 9, 10, 8, 8, 9, 6, 5, 4};

//
// To convert an array into a Set first we convert it to a List. Next
// with the list we create a HashSet and pass the list as the constructor.
//
List list = Arrays.asList(numbers);
Set set = new HashSet(list);

//
// Display what we get in the set.
//
for (Iterator iterator = set.iterator(); iterator.hasNext();) {
Object o = iterator.next();
System.out.print(o + ", ");
}
}
}

Page 1 of 212