Reka Narayanasamy

Mar 16, 20234 min

Java Collections : Map and Set Part 2

In this blog we will be learning all the operations we can do in Map and Set , this blog will be very useful for those want to learn Java Collections .

HashMap

Hash maps are a common data structure used to store key-value pairs for efficient retrieval. A value stored in a hash map is retrieved using the key under which it was stored. # `states` is a Hash Map with state abbreviation keys and state name values.

The HashMap class of the Java collections framework provides the functionality of the hash table data structure. It stores elements in key/value pairs. Here, keys are unique identifiers used to associate each value on a map. The HashMap class implements the Map interface.

It can store different types: String keys and Integer values, or the same type, like: String keys and String values:

To access a value in a HashMap, we must know its key. HashMap uses a technique called Hashing. Hashing is a technique of converting a large String to a small String that represents the same String so that the indexing and search operations are faster. HashSet also uses HashMap internally.

* The map is not the child interface of Collection.


 
* This is why it's not accepted as a true collection.


 
* The map is also used to store a group of individual objects.


 
* The main thing about Map is, it will store the records as a key-value pair.


 
* HashMap is one of the implementation classes for Map interface.

package collections;
 

 
import java.util.HashMap;
 

 
public class MapExample {
 

 
public static void main(String[] args) {
 
// TODO Auto-generated method stub
 

 
HashMap<Integer,String> employeeMap=new HashMap<Integer,String>();
 

 
// to insert an element PUT method is used
 
employeeMap.put(1, "Agni"); // entry[ key value pair stored in map]
 
employeeMap.put(2, "Riya"); // entry
 
employeeMap.put(3, "Arya"); // entry
 
employeeMap.put(4, "Athi"); // entry
 
employeeMap.put(5, "Reka"); // entry
 
employeeMap.put(1, "Agni"); // entry
 
System.out.println(" employee map:"+ employeeMap);
 

 
// to make a copy of existing map
 
HashMap<Integer,String> duplicateMap=new HashMap<Integer,String>();
 
duplicateMap.putAll(employeeMap);
 
System.out.println(" duplicate map :"+ duplicateMap);
 

 
// to clear all elements in duplicate map
 
duplicateMap.clear();
 
System.out.println(" after clearing elements in duplicate map: "+duplicateMap );
 

 
// to check if a key is present or not in the map
 
System.out.println(" does this map has key 2 ? :"+ employeeMap.containsKey(2));
 

 
//to check if a value is present or not
 
System.out.println("does this map has valur Reka? :"+ employeeMap.containsValue("Reka"));
 

 
// clone the map
 
System.out.println(" cloned map: "+employeeMap.clone() );
 

 
// CHECK IF THE MAP IS EMPTY OR NOT
 
System.out.println(" IS EMPTY? : "+employeeMap.isEmpty() );
 

 
//fetch the set of keys in the map (note : here it's not a list of keys , it's set of keys.
 
// because List will allow duplicate but Set won't. Keys should be unique.
 
System.out.println(" key set :" + employeeMap.keySet());
 

 
// fetch a value [to retieve value ]
 
System.out.println(employeeMap.get(1));
 

 
// fetch all the values
 
System.out.println(" all values :"+ employeeMap.values());
 

 
// entry set [ to retieve all key value pair]
 
System.out.println(employeeMap.entrySet());
 

 
}
 

 
}

Hash sets

Hash sets are sets that use hashes to store elements. A hashing algorithm is an algorithm that takes an element and converts it to a chunk of fixed size called a hash. Compared to a standard data structure such as a list, hash sets generally use less size, and there is always a trade-off between size and performance.

The HashSet class implements the Set interface.


 
Set(I)-> HashSet (C) and LinkedHashSet(C) are implementations
 
Set(I) -> SortedSet(Child Interface)->NavigableSet(I)=> TreeSet(C) is the implementation


 
Important points to remember:
 
*1. To store group of individual objects.
 
*2. Duplicates not allowed
 
*3.Insertion order will not be maintained
 
*4.Set(I) doesn't have any new methods other than given in Collection(I).
 
*5. DS for HashSet is Hash table( hashmap instance)
 
*6. If we add duplicate value to HashSet, simply it will return false to the
 
*add() and it won't throw any error or exception.
 
*7. We can insert null values
 
*8. Heterogeneous values can be added.
 
*9. Implements Serializable and Cloneable?-> Yes
 
*10. Data are stored based on hashcode, so search is very effective.
 
*11. Fill Ratio or Load factor:0.75 or 75%
 
*12.Default capacity-16
 

package collections;
 

 
import java.util.HashSet;
 
import java.util.Iterator;
 

 
public class SetExample {
 

 
// set(I) is one of the child interfaces of collection(I)
 
// duplicate values are not allowed
 
// insertion order is not maintained
 
//can insert Heterogeneous objects(if generics are not used)
 

 
public void basicExampleHashSet() {
 
HashSet<String> hashSet=new HashSet<String>();
 
hashSet.add("A");
 
hashSet.add("D");
 
hashSet.add("E");
 
hashSet.add("F");
 
hashSet.add("A"); // return type of add() is boolean , since A is aslready there , it will return false
 
hashSet.add(null);
 
hashSet.add("G");
 

 
// we have no control on insertion order
 
System.out.println(" contents of the hash set:"+ hashSet);
 
hashSet.remove(null);
 
System.out.println(" contents of the hash set:"+ hashSet);
 
System.out.println(hashSet.contains("A"));
 
// contains all to compare between two collection
 
// add all to add all from 1 collection to another collectio
 
}
 

 
// iterate using iterator
 
public void iterateUsingIterator() {
 
HashSet<String> hashSet=new HashSet<String>();
 
hashSet.add("A");
 
hashSet.add("D");
 
hashSet.add("E");
 
hashSet.add("F");
 
hashSet.add("A");
 

 
Iterator<String> iterator=hashSet.iterator(); //********************* NO SET ITERATOR
 
while(iterator.hasNext()) {
 
System.out.println(" elements of hash set : " +iterator.next());
 
}
 

 
}
 

 

 
public static void main(String[] args) {
 
// TODO Auto-generated method stub
 
SetExample EX= new SetExample();
 
EX.basicExampleHashSet();
 
EX.iterateUsingIterator();
 
}
 

 
}

Conclusion:

I hope, This article will help you to understand Map and Set .How to add , remove , insert , update , delete, iterate ....Please Refer Part 1 and Part 3 for more . https://www.numpyninja.com/post/java-collections-array-list-and-linked-list-part-1

https://www.numpyninja.com/post/java-collections-linked-hash-map-linked-hash-set-and-vector-part-3

https://www.numpyninja.com/post/java-collections-stack-tree-map-and-tree-set-part-4

You must have got an idea on the topics explained in this blog. Lets explore more and learn New Topics.

Happy Learning

    390
    0