Java Maps Interface

  1. An object that maps keys to values. 
  2. A map cannot contain duplicate keys
  3. each key can map to at most one value.
  4. This interface takes the place of the Dictionary class, which was a totally abstract class rather than an interface.
  5. Map doesn’t guarantee order of mappings, however it depends on the implementation. For example, HashMap doesn’t guarantee the order of mappings but TreeMap does.
  6. Map utilize hashCode and equals methods on Key for get and put operations. So mutable classes are not a good fit for Map keys. If the values of hashCode or equals change after put, you won’t get the correct value in get operation
Why and when to use maps?
  1. A map of error codes and their descriptions.
  2. A map of zip codes and cities.
  3. A map of employees and employee ID.
  4. A map of classes and students.
Hierarchy of Maps:
Methods of Map:
1) Object put(Object key, Object value) : is used to insert an entry in this map.

2) void putAll(Map map) : is used to insert the specified map in this map.

3) Object remove(Object key) : is used to delete an entry for the specified key.

4) Object get(Object key) : is used to return the value for the specified key.

5) boolean containsKey(Object key) : is used to search the specified key from this map.

6) boolean containsValue(Object value): returns true if there are at least one key mapped to the specified value, otherwise false.

7) Set keySet() : returns the Set view containing all the keys.

8) Set entrySet() : returns the Set view containing all the keys and values.

9) int size(): returns the number of key-value mappings in this Map.

10) boolean isEmpty(): returns true if there are no mappings present, otherwise false.

11) void clear(): removes all the mappings from the Map.

10) Collection<V> values(): returns the collection view of all the values in the Map. This collection is backed by Map, so any change in Map will reflect to this values collection and vice versa.

11) Set<Map.Entry<K, V>> entrySet(): returns the Set view of the mappings in the Map. This Set is backed by Map, so any modifications in Map will be reflected in the entry set and vice versa.

Maps are further classified into the following:
  1. HashMap
  2. LinkedHashMap
  3. HashTable
  4. TreeMap

HashMap and Hashtable doesn’t maintain any order.
TreeMap sort the entries in ascending order of keys.
LinkedHashMap maintains the insertion order.

 Let’s go into detail on each one of them:

1) HashMap
  1. A HashMap stores Key & value pairs.
  2. It contains only unique elements.
  3. It maintains no order.
  4. It is similar to the Hashtable class except that it is unsynchronized and permits nulls
  5. It may have one null key and multiple null values.
Declaration:
HashMap<Integer, String> hm = new HashMap<>();
or
Map m1 = new HashMap();

HashMap Examples:
1) Add element and traverse through HashMap
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import java.util.*;

public class HashMap_Demo {

 public static void main(String[] args) {

  HashMap<Integer, String> map = new HashMap<>();
  map.put(3, "Vinod");
  map.put(6, "Amol");
  map.put(8, "Nandan");
  map.put(12, "Yusuf");

  // Iterating over hashmap
  for (Map.Entry<Integer, String> entry : map.entrySet()) {
   Integer key = entry.getKey();
   String value = entry.getValue();
   System.out.println(key + " " + value);
  }

  System.out.println("HashMap size= " + map.size());
  
  // Checking and searching
  if (map.containsKey(8)) {
   System.out.println("HashMap has a given key");
  } else {
   System.out.println("HashMap hasn't a given key");
  }

  // Remove the content of the hashMap
  map.clear();

  // Check if the hashMap empty
  if (map.isEmpty())
  {
   System.out.println("The hashMap is empty");
  }
 }
}

The following code snippets will show you at least 3 different ways of storing key-value pairs with a distinction of Single Key and Multiple Values.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import java.util.*;
import java.util.Map.Entry;

public class HashMap_Demo2 {
 public static void main(String[] args) {

  // create map to store
  Map<String, List<String>> map = new HashMap<String, List<String>>();

  // create list one and store values
  List<String> valSetOne = new ArrayList<String>();

  valSetOne.add("Apple");
  valSetOne.add("Aeroplane");

  // create list two and store values
  List<String> valSetTwo = new ArrayList<String>();
  valSetTwo.add("Bat");
  valSetTwo.add("Banana");

  // create list three and store values
  List<String> valSetThree = new ArrayList<String>();
  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<String, List<String>> entry : map.entrySet()) {
   String key = entry.getKey();
   List<String> values = entry.getValue();
   System.out.println("Key = " + key);
   System.out.println("Values = " + values + "\n");
  }
 }
}

2) LinkedHashMap
  1. A LinkedHashMap contains values based on the key.
  2. It may have one null key and multiple null values.
  3. This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries.
  4. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order).
Declaration:
LinkedHashMap<Integer, String> lhmap = new LinkedHashMap<Integer, String>();

LinkedHashMap Examples:
1) Add element and traverse through LinkedHashMap

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import java.util.LinkedHashMap;
import java.util.Map;

public class LinkedHashMapDemo {

 public static void main(String[] args) {
  LinkedHashMap<Integer, String> map = new LinkedHashMap<>();

  map.put(3, "Vinod");
  map.put(6, "Amol");
  map.put(8, "Nandan");
  map.put(12, "Yusuf");

  // Iterating over linkedHashMap
  for (Map.Entry<Integer, String> entry : map.entrySet()) {
   Integer key = entry.getKey();
   String value = entry.getValue();
   System.out.println(key + " " + value);
  }

  System.out.println("LinkedHashMap size= " + map.size());

  // Checking and searching
  if (map.containsKey(8)) {
   System.out.println("LinkedHashMap has a given key");
  } else {
   System.out.println("LinkedHashMap hasn't a given key");
  }

  // Remove the content of the LinkedhashMap
  map.clear();

  // Check if the LinkedhashMap empty
  if (map.isEmpty()){
   System.out.println("The LinkedhashMap is empty");
  }
 }
}

Output:
3 Vinod
6 Amol
8 Nandan
12 Yusuf
LinkedHashMap size= 4
LinkedHashMap has a given key
The LinkedhashMap is empty

3) TreeMap
  1. TreeMap class implements Map interface similar to HashMap class. 
  2. The main difference between them is that HashMap is an unordered collection while TreeMap is sorted in the ascending order of its keys.
  3. TreeMap is unsynchronized collection class.
Declaration:
TreeMap<Integer, String> tmap = new TreeMap<Integer, String>();

TreeMap Examples:

1) Add element and traverse through TreeMap.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import java.util.Map;
import java.util.TreeMap;

public class TreeMapDemo {

 public static void main(String[] args) {

  TreeMap<Integer, String> tmap = new TreeMap();
  tmap.put(33, "Pune");
  tmap.put(11, "Mumbai");
  tmap.put(44, "Nagpur");
  tmap.put(22, "Nasik");

  // Iterating over hashmap
  for (Map.Entry<Integer, String> entry : tmap.entrySet()) {
   Integer key = entry.getKey();
   String value = entry.getValue();
   System.out.println(key + " " + value);
  }

  System.out.println("LinkedHashMap size= " + tmap.size());

  // Checking and searching
  if (tmap.containsKey(22)) {
   System.out.println("LinkedHashMap has a given key");
  } else {
   System.out.println("LinkedHashMap hasn't a given key");
  }

  // Remove the content of the hashMap
  tmap.clear();

  // Check if the hashMap empty
  if (tmap.isEmpty()){
   System.out.println("The LinkedhashMap is empty");
  }
 }
}

Output:
11 Mumbai
22 Nasik
33 Pune
44 Nagpur
LinkedHashMap size= 4
LinkedHashMap has a given key

The LinkedhashMap is empty

4) HashTable
  1. Java Hashtable class implements a hashtable, which maps keys to values. 
  2. It inherits Dictionary class and implements the Map interface.
  3. Any non-null object can be used as a key or as a value.
  4. It contains only unique elements.
  5. It may have not have any null key or value.
  6. It is synchronized an thread-safe.
Declaration:
Hashtable<Integer,String> hm=new Hashtable<Integer,String>();  

Hashtable Examples:

1) Add element and traverse through Hashtable.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import java.util.Hashtable;
import java.util.Map.Entry;

public class HashTableDemo {

 public static void main(String[] args) {

  Hashtable<Integer, String> htable = new Hashtable<>();
  htable.put(3, "Vinod");
  htable.put(6, "Amol");
  htable.put(8, "Nandan");
  htable.put(12, "Yusuf");

  // Iterating over Hashtable
  for (Entry<Integer, String> entry : htable.entrySet()) {
   Integer key = entry.getKey();
   String value = entry.getValue();
   System.out.println(key + " " + value);
  }

  System.out.println("Hashtable size= " + htable.size());

  // Checking and searching
  if (map.containsKey(8)) {
   System.out.println("Hashtable has a given key");
  } else {
   System.out.println("Hashtable hasn't a given key");
  }

  // Remove the content of the Hashtable
  htable.clear();

  // Check if the Hashtable empty
  if (htable.isEmpty()){
   System.out.println("The Hashtable is empty");
  }
 }
}
Output:
8 Nandan
6 Amol
3 Vinod
12 Yusuf
Hashtable size= 4
Hashtable has a given key
The Hashtable is empty



<-- Previous || Next -->

No comments:

Post a Comment