HashMap And TreeMap in Java
Map in Java is used to store key, value pairs.
1. HashMap:
Java HashMap class implements the Map interface which allows us to store key and value pair, where keys should be unique. If you try to insert the duplicate key, it will replace the element of the corresponding key.
Note: We can store null values and only one null key.
Syntax:
Map<K,V> map = new HashMap<K,V>();
OR
HashMap<K,V> map = new HashMap<K, V>();
Here K is type of Key and V is the type of Value.
Below are some useful methods of HashMap class:
HashMap<Integer, String> map = new HashMap<>();
- put(K key, V value) : used to add a new value associated with the key
map.put(1, "one");
map.put(2, "two");
System.out.println( map ); //output: {1: one, 2:two}
- get(K key): retrieves the value associated with the key from map if exists otherwise returns null
map.get(1); //returns "one"
- get(K key,V default): if key exists on the map, then returns associated value otherwise returns a default value
map.get(3, "default") //returns default because 3 does not exists in the map
- isEmpty() : returns true if map has no key value pair, otherwise returns false.
- containsKey(K key): returns true if map contains specified key, otherwise returns false
- containsValue(V value): returns true if any key contains the value, otherwise returns false
- remove(K Key): removes key and its value form the map if exists
- remove(K key, V value): removes key if it has the same value specified as second parameter
- size(): returns number of key value pairs inside the map
- keySet(): returns the Set view of all the keys contained in the map
2. TreeMap:
Java TreeMap provides an efficient means of storing key-value pairs in a sorted order. Basically it implements the functionality of red-black tree.
Note: It cannot contain a null value as key.
- By default it stored key-values in ascending order of their key.
Syntax:
TreeMap<K,V> map = new TreeMap<K,V>();
TreeMap supports same methods we defined above for HashMap.
Example:
TreeMap<String, Integer> map = new TreeMap<>();
map.put("one", 1);
map.put("two", 2);
map.put("three", 3);
map.put("four", 4);
System.out.println(map);
//output: {four=4, one=1, three=3, two=2}
Comments
Post a Comment