Kotlin HashMap classKotlin HashMap is class of collection based on MutableMap interface. Kotlin HashMap class implements the MutableMap interface using Hash table. It store the data in the form of key and value pair. It is represented as HashMap<key, value> or HashMap<K, V>. The implementation of HashMap class does not make guarantees about the order of data of key, value and entries of collections. Constructor of Kotlin HashMap class
Functions of Kotlin HashMap class
Kotlin HashMap Example 1- empty HashMapLet's create a simple example of HashMap class define with empty HashMap of <Int, String> and add elements later. To print the value of HashMap we will either use HashMap[key] or HashMap.get(key). Output: .....traversing hashmap....... Element at key 1 = Ajay Element at key 2 = Ajay Element at key 3 = Vijay Element at key 4 = Praveen Kotlin HashMap Example 2- HashMap initial capacityHashMap can also be initialize with its initial capacity. The capacity can be changed by adding and replacing its element. Output: .....traversing hashmap....... Element at key name = Ajay Element at key department = Software Development Element at key city = Delhi .....hashMap.size....... 3 .....hashMap.size after adding hobby....... 4 .....traversing hashmap....... Element at key name = Ajay Element at key department = Software Development Element at key city = Delhi Element at key hobby = Travelling Kotlin HashMap Example 3- remove() and put()The function remove() is used to replace the existing value at specified key with specified value. The put() function add a new value at specified key and replace the old value. If put() function does not found any specified key, it put a new value at specified key. Output: .....traversing hashmap....... Element at key 1 = Ajay Element at key 2 = Rohan Element at key 3 = Vijay Element at key 4 = Prakash .....hashMap.replace(3,"Ashu")...hashMap.put(2,"Raj").... Element at key 1 = Ajay Element at key 2 = Raj Element at key 3 = Ashu Element at key 4 = Prakash Kotlin HashMap Example 4 - containsKey(key) and containsValue(value)The Function containsKey() returns true if the specified key is present in HashMap or returns false if no such key exist. The Function containsValue() is used to check whether the specified value is exist in HashMap or not. If value exists in HashMap, it will returns true else returns false. Output: .....traversing hashmap....... Element at key 1 = Ajay Element at key 2 = Rohan Element at key 3 = Vijay Element at key 4 = Prakash .....hashMap.containsKey(3)....... true .....hashMap.containsValue("Rohan")....... true Kotlin HashMap Example 5 - clear()The clear() function is used to clear all the data from the HashMap. Output: .....traversing hashmap....... Element at key 1 = Ajay Element at key 2 = Rohan Element at key 3 = Vijay Element at key 4 = Prakash .....hashMap.clear()....... .....print hashMap after clear()....... {} Next TopicKotlin HashMap: hashMapOf() |