· 6 years ago · Apr 21, 2019, 04:38 AM
1|----------> HashMap class implements Map
2Map(Interface) |----------> HashTable class implements Map
3 |----------> WeakHashMap class implements Map
4 |----------> SortedMap interface extends Map --> TreeMap class implements SortedMap
5 |----------> LinkedHashMap implements Map
6
7
8A map stores pairs of keys and values. Each key-value pair is unique. Maps can not store duplicates.
9Example; A translation program could be written using a map.
10
11You can specify type of reference you want to store in TreeMap or HashMap.
12Map<String, Integer> hash = new HashMap<String, Integer>();
13Map<String, Set> tree = new TreeMap<String, TreeSet<String>>();
14
15HashMap --> A map ordered by each item's hashCode that is extremely time efficient.
16TreeMap --> A naturally ordered map that is very efficient, but not as efficient as HashMap.
17
18Differences between HashMap and Hashtable:
19-----------------------------------------
201. Synchronization or Thread Safe : This is the most important difference between two . HashMap is non synchronized and
21not thread safe.On the other hand, Hashtable is thread safe and synchronized.
22
23When to use HashMap ? answer is if your application do not require any multi-threading task,
24in other words HashMap is better for non-threading applications. Hashtable should be used in multithreading applications.
25
262. Null keys and null values : HashMap allows one null key and any number of null values,
27while Hashtable do not allow null keys and null values in the Hashtable object.
28
293. Iterating the values: HashMap object values are iterated by using iterator .Hashtable is the only class other than vector
30which uses enumerator to iterate the values of Hashtable object
31
324. Fail-fast iterator : The iterator in HashMap is fail-fast iterator while the enumerator for Hashtable is not.
33
345. Performance : HashMap is much faster and uses less memory than Hashtable as former is unsynchronized .
35Unsynchronized objects are often much better in performance in compare to synchronized object like Hashtable
36in single threaded environment.
37
386. Superclass and Legacy : Hashtable is a subclass of Dictionary class which is now obsolete in Jdk 1.7 ,so ,it is not used anymore.
39There's nothing about Hashtable that can't be done using HashMap or derivations of HashMap.
40It is better off externally synchronizing a HashMap or using a ConcurrentMap implementation (e.g ConcurrentHashMap).
41HashMap is the subclass of the AbstractMap class. Although Hashtable and HashMap has different superclasses but
42they both are implementations of the "Map" abstract data type.
43
44Example:
45public static void main(String args[])
46 {
47 //----------hashtable -------------------------
48 Hashtable<Integer,String> ht=new Hashtable<Integer,String>();
49 ht.put(101," ajay");
50 ht.put(101,"Vijay");
51 ht.put(102,"Ravi");
52 ht.put(103,"Rahul");
53 System.out.println("-------------Hash table--------------");
54 for (Map.Entry m:ht.entrySet()) {
55 System.out.println(m.getKey()+" "+m.getValue());
56 }
57
58 //----------------hashmap--------------------------------
59 HashMap<Integer,String> hm=new HashMap<Integer,String>();
60 hm.put(100,"Amit");
61 hm.put(104,"Amit"); // hash map allows duplicate values
62 hm.put(101,"Vijay");
63 hm.put(102,"Rahul");
64 System.out.println("-----------Hash map-----------");
65 for (Map.Entry m:hm.entrySet()) {
66 System.out.println(m.getKey()+" "+m.getValue());
67 }
68 }
69
70
71
72Some Map methods:
73put(x,y) --> adds the <x,y> pair to the map
74get(x) --> gets the value for key x
75clear() --> removes all items from the set
76size() --> returns the # of items in the set
77keySet() --> returns a set of all keys in the map
78containsKey() --> checks if key x is in the map
79
80
81Map<Character, Integer> map = new TreeMap<Character, Integer>();
82String s = "alkjfkjslsj";
83for(char c:s.toCharArray()){
84 if(map.get(c) == null) map.put(c,0);
85 map.put(c, map.get(c)+1);
86}
87
88==============================
89A map is a data structure that's is designed for fast lookup. Data is stored in key-value pairs with
90every key being unique.
91
92Map is the only collection that doesn't extend or implement the collection interface.
93
94The keys and values of a map can be any reference type. We can't use primitive types. A HashMap allows
95one null key and multiple null values. It doesn't preserve the order of the elements and doesn't guarantee
96the order will remain the same over time.
97
98To create;
99Map<Integer, String> map = new HashMap<>();
100map.put(1, "Petyr Baelish");
101map.put(2, "Sansa Stark");
102map.put(3, "Jon Snow");
103map.put(4, "Jamie Lannister");
104
105Sometimes we may want to add multiple entries in bulk or combine two maps.
106There's a method that handles this called putAll().
107It copies the entry references from another map in order to populate ours.
108
109To check whether a key already exists, we use the containsKey() boolean method:
110if (map.containsKey(4)) {
111 throw new IllegalArgumentException("Unable to add character, duplicate id");
112}
113
114Similarly, the containsValue() method checks for existence of a value:
115boolean check = map.containsValue("Brienne of Tarth"); // false
116
117Some methods:
118map.get(4); --> Returns the value
119map.remove(3); --> Removes the value
120map.clear(); --> Empty the map
121map.size() -->Returns number of entries
122map.isEmpty() --> Returns a boolean indicating if the map is empty or not
123
124Collection Views:
125 The Map interface provides Collection view methods which allow us to view our map in terms of a
126 collection type.
127 keySet() --> Returns a Set of keys from the map
128 values() --> Returns a Collection of values from the map
129 entrySet() --> Returns a Set of Map.Entry objects which represent the key-value pairs in the map.
130
131Set<Integer> keys = map.keySet(); // [1,2,5]
132Collection<String> values = map.values(); // [Petyr Baelish, Sansa Stark, Daenerys Targaryen]
133
134===Iterating over a Map:
135There are many ways, lets go over some.
136Keep in mind that loops will throw a NullPointerException if we try to iterate over a map that is null.
137
138Using foreach and Map.Entry;
139for (Map.Entry entry : map.entrySet()) {
140 System.out.println( entry.getKey() + " -> " + entry.getValue() );
141}
142
143Using jav8 Lambda expression;
144map.forEach((k,v) -> System.out.println("key: " + k + ", value: " + v));
145
146To convert map;
147treeMap.putAll(hashMap);
148
149=========================================================================
150Example:
151
152public class SpanishToEnglish {
153 private static Map<String, String> pairs = new TreeMap<String, String>();
154
155 public static void main(String[] args) throws IOException {
156 Scanner file = new Scanner(new File("spantoeng.dat"));
157
158 int num = file.nextInt();
159 file.nextLine();
160 for (int i = 0; i < num; i++) {
161 putEntry(file.nextLine());
162 }
163 }
164
165 public static void putEntry(String entry) {
166 String[] list = entry.split(" ");
167 String key = list[0];
168 String value = list[1];
169 pairs.put(key, value);
170 }
171
172 public static String translate(String sent) {
173
174 Scanner chop = new Scanner(sent);
175 String output = "";
176 while (chop.hasNext()) {
177 output += pairs.get(chop.next()) + " ";
178 }
179 return output;
180 }
181
182 public String toString() {
183 return pairs.toString().replaceAll("\\", "\n");
184 }
185}