Map implementations

Map
An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value.
This interface takes the place of the Dictionary class, which was a totally abstract class rather than an interface.
The Map interface provides three collection views, which allow a map's contents to be viewed as a set of keys, collection of values, or set of key-value mappings. The order of a map is defined as the order in which the iterators on the map's collection views return their elements. Some map implementations, like the TreeMap class, make specific guarantees as to their order; others, like the HashMap class, do not.
Note: great care must be exercised if mutable objects are used as map keys. The behavior of a map is not specified if the value of an object is changed in a manner that affects equals comparisons while the object is a key in the map. A special case of this prohibition is that it is not permissible for a map to contain itself as a key. While it is permissible for a map to contain itself as a value, extreme caution is advised: the equals and hashCode methods are no longer well defined on a such a map.
All general-purpose map implementation classes should provide two "standard" constructors: a void (no arguments) constructor which creates an empty map, and a constructor with a single argument of type Map, which creates a new map with the same key-value mappings as its argument. In effect, the latter constructor allows the user to copy any map, producing an equivalent map of the desired class. There is no way to enforce this recommendation (as interfaces cannot contain constructors) but all of the general-purpose map implementations in the SDK comply.
Basic Methods
A map has the form Map where:
* K: specifies the type of keys maintained in this map
* V: defines the type of mapped values.
The Map interface provides a set of methods that must be implemented
* clear: Removes all the elements from the map.
* containsKey: Returns true if the map contains the requested key.
* containsValue: Returns true if the map contains the requested value.
* equals: Compares an Object with the map for equality.
* get: Retrieve the value of the requested key.
* keySet: Returns a Set that contains all keys of the map.
* put: Adds the requested key-value pair in the map.
* remove: Removes the requested key and its value from the map, if the key exists.
* size: Returns the number of key-value pairs currently in the map.
There are many classes that implement the Java Map interface. These are given below: -
1. Hash Map: - The most common class that implements the Map interface is the Java HashMap. A HashMap is a hash table based implementation of the Map interface. It permits null keys and values. Also, this class does not maintain any order among its elements and especially, it does not guarantee that the order will remain constant over time. Finally, a HashMap contains two fundamental parameters: initial capacity and performance. The capacity is defined as the number of buckets in the hash table, while the load factor is a measure that indicates the maximum value the hash table can reach, before being automatically increased.
Example: -
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class skvp {
public static void main(String[] args) {
// create map to store
Map> map = new HashMap>();
// create list one and store values
List valSetOne = new ArrayList();
valSetOne.add("Apple");
valSetOne.add("Aeroplane");
// create list two and store values
List valSetTwo = new ArrayList();
valSetTwo.add("Bat");
valSetTwo.add("Banana");
// create list three and store values
List valSetThree = new ArrayList();
valSetThree.add("Cat");
valSetThree.add("Car");
// put values into map
map.put("A", valSetOne);
map.put("B", valSetTwo);
map.put("C", valSetThree);
// iterate and display values
System.out.println("Fetching Keys and corresponding [Multiple] Values n");
for (Map.Entry> entry : map.entrySet()) {
String key = entry.getKey();
List values = entry.getValue();
System.out.println("Key = " + key);
System.out.println("Values = " + values + "n");
}
}
}
Output: -
C:\java>javac skvp.java
C:\java>java skvp
Fetching Keys and corresponding [Multiple] Values n
Key = A
Values = [Apple, Aeroplane]n
Key = B
Values = [Bat, Banana]n
Key = C
Values = [Cat, Car]n
2. HashTable: - The HashTable class implements a hash table and maps keys to values. However, neither the key nor the value can be null. This class contains two fundamental parameters: initial capacity and performance, with the same definitions as the HashMap class.
Example: -
import java.util.Collection;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Set;
class HashtableDemo {
public static void main(String args[]) {
// Creating Hashtable for example
Hashtable companies = new Hashtable();
// Java Hashtable example to put object into Hashtable
// put(key, value) is used to insert object into map
companies.put("Google", "United States");
companies.put("Nokia", "Finland");
companies.put("Sony", "Japan");
// Java Hashtable example to get Object from Hashtable
// get(key) method is used to retrieve Objects from Hashtable
companies.get("Google");
// Hashtable containsKey Example
// Use containsKey(Object) method to check if an Object exits as key in
// hashtable
System.out.println("Does hashtable contains Google as key: "
+ companies.containsKey("Google"));
// Hashtable containsValue Example
// just like containsKey(), containsValue returns true if hashtable
// contains specified object as value
System.out.println("Does hashtable contains Japan as value: "
+ companies.containsValue("Japan"));
// Hashtable enumeration Example
// hashtabl.elements() return enumeration of all hashtable values
Enumeration enumeration = companies.elements();
while (enumeration.hasMoreElements()) {
System.out.println("hashtable values: " + enumeration.nextElement());
}
// How to check if Hashtable is empty in Java
// use isEmpty method of hashtable to check emptiness of hashtable in
// Java
System.out.println("Is companies hashtable empty: "+ companies.isEmpty());
// How to find size of Hashtable in Java
// use hashtable.size() method to find size of hashtable in Java
System.out.println("Size of hashtable in Java: " + companies.size());
// How to get all values form hashtable in Java
// you can use keySet() method to get a Set of all the keys of hashtable
// in Java
Set hashtableKeys = companies.keySet();
// you can also get enumeration of all keys by using method keys()
Enumeration hashtableKeysEnum = companies.keys();
// How to get all keys from hashtable in Java
// There are two ways to get all values form hashtalbe first by using
// Enumeration and second getting values ad Collection
Enumeration hashtableValuesEnum = companies.elements();
Collection hashtableValues = companies.values();
// Hashtable clear example
// by using clear() we can reuse an existing hashtable, it clears all
// mappings.
companies.clear();
}
}
Output: -
C:\java>javac HashtableDemo.java
C:\java>java HashtableDemo
Does hashtable contains Google as key: true
Does hashtable contains Japan as value: true
hashtable values: Finland
hashtable values: United States
hashtable values: Japan
Is companies hashtable empty: false
Size of hashtable in Java: 3
3. ConcurrentHashMap: - The class is a hash table that supports full concurrency of retrievals. Thus, this structure is safe to use in case of multiple threads. Finally, this class does not allow neither keys nor values to be null.
Example: -
import java.util.Map;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;
final class ConcurrentHashMapExample {
private ConcurrentHashMapExample() {
}
public static void main(String[] args) throws InterruptedException {
for (int i = 0; i < 100; i++) {
System.out.println("ConcurrentHashMap is Thread safe.");
ConcurrentHashMap cmap = new ConcurrentHashMap();
Thread ct1 = new Thread(new CreateMapTask(cmap));
Thread ct2 = new Thread(new CreateMapTask(cmap));
ct1.start();
ct2.start();
ct1.join();
ct2.join();
System.out.println("HashMap might cause an infinite loop.");
HashMap map = new HashMap();
Thread t1 = new Thread(new CreateMapTask(map));
Thread t2 = new Thread(new CreateMapTask(map));
t1.start();
t2.start();
t1.join();
t2.join();
}
}
private static class CreateMapTask implements Runnable {
private Map map;
public CreateMapTask(Map map) {
this.map = map;
}
public void run() {
for (int i = 0; i < 1000000; i++) {
int k = i % 10000;
if (map.containsKey(k)) {
map.remove(k);
} else {
map.put(k, i);
}
}
}
}
}
Output: -
C:\java>javac abc.java
C:\java>java ConcurrentHashMapExample
ConcurrentHashMap is Thread safe.
HashMap might cause an infinite loop.
ConcurrentHashMap is Thread safe.
HashMap might cause an infinite loop.
ConcurrentHashMap is Thread safe.
HashMap might cause an infinite loop.
ConcurrentHashMap is Thread safe.


Free Web Hosting