Map and Set in Java - made easy

This post will teach you how and where to use Map and Set in Java. I have written in the simplest possible way. Please note that this post won't deal with internal implementation of Maps and Sets.

MAP


Definition


A Map is an Interface in which an object maps keys to values.


Use

A map is basically used when we need to store the particular occurrence of some variables. For e.g.: - Write a program to find the occurrence of all the words in a file. In this program we will put all the words in the map and whenever we find an occurrence will increment the value.


Types

The basic different types of Maps in Java are HashMap, TreeMap and LinkedHashMap.

HashMap - HashMap is implemented using a Hash Table. The insertion and retrieval time in HashMap is O(1). When you traverse the elements, there won't be a specific order.

TreeMap - Implemented Using Red-Black-Tree. The insertion and retrieval time in TreeMap is O(log n). Sorted order.

For more about Red- Black - Tree, please refer 4.

LinkedHashMap - Implemented Using Linked List and Hash Table. Insertion and retrieval time is O(1). Returns the order in which you inserted.

Usage

Now, I believe you have got a basic idea about Maps. The next thing is how to use the Map. We just need to know three things for using a Map. They are:



  • Defining a Map
  • Insertion and Retrieval of elements in Map
  • Traversing a Map

 For using a map interface we need to the following import - import java.util.Map;

Define a Map


The line below will define a TreeMap.



Map<Integer,Integer> Clustermap = new TreeMap<Integer,Integer>();

For defining a HashMap, you can use HashMap instead of TreeMap. Same for LinkedHashMap. Instead of Integer, we can use String, Double,Char etc.

For importing TreeMap Use - import java.util.TreeMap;

Adding a value to Map

Clustermap.put(20, 30);
Here 20 is the key and 30 is the value.

Checking a value or key in a Map

boolean find =Clustermap.containsKey(20);
boolean find1= Clustermap.containsValue(30);

If value or key is present in the Map, true value will be returned.


Retrieving a value in a Map



int item=Clustermap.get(2);

The variable 'item' will have the corresponding value of the key 2.

Iterating a Map

One of the main problem I found in people using maps is how to iterate the maps. The following piece of code is the most common way of iterating a map.



for(Map.Entry<Integer, Integer> entry: Clustermap.entrySet())
{
System.out.println(" Gene Id = "+entry.getKey() + " Cluster number = "+entry.getValue());

}

Here the Map is iterated based on each entry. Other methods of iterating a map is given in Reference 3.

I believe you got the basic idea of how to use Map in Java. There are many other methods in Map, which are not commonly used. For becoming more thorough in Map, it is advisable to do more coding using Maps. Please comment below if you have any doubts.

SET

Definition

A Set is an Interface which does not contain unique elements.

Use

A set is mainly used whenever we want to get the unique elements from a group of elements. For e.g.:- A program to print unique elements in an array.

Types
Like Map, there are 3 different types of Set. They are HashSet, TreeSet and LinkedHashSet.

HashSet - Implemented using a HashMap. Insertion and retrieval of elements take place in O(1). Doesn't have an order while traversing

TreeSet - Implemented using a TreeMap. Insertion and retrieval of elements take place in O(log n). It will traverse the elements in a suitable order.

LinkedHashSet - Implemented using a Linked List and HashMap. Insertion and retrieval of elements same as HashSet. While traversing, prints in the order in which elements are inserted.

Usage

Similar to Maps, for using Sets, we only need to know how to define a set, how to insert and retrieve an element in set and how to traverse a set.

For using a set interface, we need to do import import java.util.Set;

Defining a set

The line below will define a Set.

Set<Integer> newset = new HashSet<Integer>();



For defining a TreeSet, you can use TreeSet instead of HashSet. Same for LinkedHashSet. Instead of Integer, we can use String, Double,Char etc.

Inserting and checking for an element in Set

For inserting an element - newset.add(10);

For checking whether an element exists in Setboolean find = newset.contains(1);
If find returns true, the element is there in the set.

Traversing a Set

Following line will traverse a linked list



  for(Integer elem: newset)

{

System.out.println(elem);

}

A sample program which uses both Map and Set - http://sujithforu.blogspot.com/2012/10/duplicate-values-in-array.html


Please Comment below if you have any doubts. All comments will be responded within 24 hours. Thank you for reading.

References: 


1) http://docs.oracle.com/javase/6/docs/api/java/util/Map.html

2) http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Set.html
3) http://www.sergiy.ca/how-to-iterate-over-a-map-in-java/
4) http://en.wikipedia.org/wiki/Red%E2%80%93black_tree


Comments

  1. Maps are explained well! Can you point to some starter questions to work with?

    ReplyDelete
  2. Thanks for commenting here. Some starter questions in maps - 1) Given an array [10,6,4,3,5,6,3,4,8,9,10,11,12], find the duplicate elements in the array or find the unique elements in an array. 2) Check whether 2 strings are anagram.

    ReplyDelete

Post a Comment

Popular posts from this blog

Difference between "diff" and "sdiff" commands in Unix

Anonymous classes in C++