You are on page 1of 107

COLLECTIONS

(An easy way to manage


Objects)
What Is A Collection ?
As the name indicates,a collection is a group of objects
known as its elements. Examples of collections are :
1. List of email ids
2. List Of Names
3. List of phone numbers
4. Records Of Students
5. Records of books . etc
How Java supports Collections ?
To handle such collection of objects, Java offers us a huge
set of predefined classes and interfaces called as
“The Collections Framework”

which is available in the package “java.util”


Why do we need to learn Collection ?
The first question which comes in mind of every programmer is
Why should I use Collection classes when I have an array ?
Answer:
Although arrays are very useful data storage structures but they
suffer from several important drawbacks which are:
1.Size needs to be declared at the time of declaration, so can only
be used if we know beforehand how many elements we would be
storing
2.Remains of fixed size
3. Very difficult to add or remove elements in between
4. No predefined methods for performing common operations like
searching, sorting , removing etc
Advantages Of Collections

1. Can dynamically grow or shrink

2. Reduces programming effort

3. Increases program speed and quality

4. Provide predefined methods to perform all C R U D


operations
Types Of Collections
There are 3 main types of collections:

• Lists: always ordered, may contain duplicates and can be


handled the same way as usual arrays
• Sets: cannot contain duplicates and provide random
access to their elements
• Maps: connect unique keys with values, provide random
access to its keys
The Collection Hierarchy
The Collection Classes
The Map Classes
Quiz
1. The core collection interfaces are organized into two
distinct inheritance trees. One interface in particular is
not considered to be a true Collection, and therefore sits
at the top of its own tree. What is the name of this
interface?

Answer: Map
Quiz
2. What interface represents a collection that does not
allow duplicate elements?

Answer: Set

3 What interface forms the root of the collections


hierarchy?

Answer: Collection
Quiz
4 What interface represents an ordered collection that
may contain duplicate elements?

Answer: List

5. What interface represents a collection that holds


elements prior to processing?

Answer: Queue
Quiz

6. Which interface in Collections extends RandomAccess


?
Answer: None ! , It is extended by ArrayList and Vector
classes

7. What is the difference between Collection and


Collections ?

Answer: First is an interface while second is a class


Quiz

8. Which classes in Collections hierarchy are thread-safe


?

Answer: Vector
Quiz
9. Difference between ArrayList and LinkedList
Answer:
ArrayList LinkedList
Backed by growable Array Backed by Doubly Linked
List
Allows random access Does give a get() method
using get() method but internally traverses from
head to tail
Faster in retrieval but Slower in retrieval but faster
slower in addition and in addition and deletion
deletion
Uses less memory Uses more memory as it
also maintains references to
previous and next nodes
Quiz
10. Difference between HashSet and TreeSet
Answer:

HashSet TreeSet
Maintains elements in Maintains elements in
random order sorted order
Allows null Doesn’t allows null

Backed by HashMap Backed by binary tree

Faster Slower

Less functionality Rich in functionality


Quiz
11. .Which collection class allows you to grow or shrink its
size and provides indexed access to its elements, but
whose methods are not synchronized?
a)java.util.HashSet
b)java.util.LinkedHashSet
c)java.util.List
d)java.util.ArrayList
Answer: d) java.util.ArrayList
Quiz
12. . You need to store elements in a collection that
guarantees that no duplicates are stored and all
elements can be accessed in natural order. Which
interface provides that capability?
a)java.util.Map
b)java.util.Set
c)java.util.List
d)java.util.Collection
Answer: b) java.util.Set
Important Methods Of Collections
The Collection interface is one of the root interfaces of the Java collection
classes. The general methods list of the collection interface is:
1. boolean add(Object obj)
2. boolean addAll(Collection c)
3. void clear( )
4. boolean contains(Object obj)
5. boolean containsAll(Collection c)
6. boolean equals(Object obj)
7. int hashCode( )
8. boolean isEmpty( )
9. Iterator iterator( )
10. boolean remove(Object obj)
11. boolean removeAll(Collection c)
12. boolean retainAll(Collection c)
13. int size( )
14. Object[ ] toArray( )
The List Interface
• The java.util.List interface is a subtype of the
java.util.Collection interface and represents an ordered
collection (sometimes called a sequence).
• It means we can access the elements of a List in a
specific order, and by an index too.
• It allows duplicate objects and one or more elements to
be null.
• The user of this interface has precise control over where
in the list each element is inserted and can access
elements by their integer index (position in the list), and
search for elements in the list.
Implementation Classes Of “List”
We can choose between the following List implementations
in the Java Collections API:
java.util.ArrayList
java.util.LinkedList
java.util.Vector
java.util.Stack

Here are a few examples of how to create a List instance:


List listA = new ArrayList();
List listB = new LinkedList();
List listC = new Vector();
List listD = new Stack();
The “ArrayList” class
• ArrayList implements List interface.

• ArrayList capacity grows automatically.

• The ArrayList is not synchronized.

• It permits all elements including null.

• Array lists are created with an initial size of 10

• When this size is exceeded, the collection is automatically


enlarged and when objects are removed, the array may be
shrunk.
Creating The “ArrayList” Object
• We can create an ArrayList object in 2 ways:
Empty ArrayList with
initial capacity of 10
• Without using type parameter (old way)
• ArrayList
This cities=new ArrayList( );
is called type
parameter

• Using type parameter (new and recommended


way)
• ArrayList <String> cities=new ArrayList<String>( );

• Both are permitted but type safe (generic) is


recommended because of enhanced type-safety.
Putting Elements In ArrayList
• To insert elements in the ArrayList we can call it’s
add( ) method.

• The prototype of the method is :


• public boolean add(Object)
• Example:
• cities.add(“Bhopal”);
• cities.add(“Delhi”);

• The size increased when the element is added


Program
import java.util.*;
class ArrayListDemo
{
public static void main(String[] args)
This output is coming
{
from toString( )
ArrayList <String>cities = new ArrayList<String>();
method of ArrayList
cities.add(“Bhopal”);
cities.add(“Paris”);
cities.add(“Delhi”)
System.out.println("The ArrayList Elements are : " +cities);
}
}
Output:
The ArrayList Elements are : [Bhopal, Paris,Delhi]
Checking size of ArrayList
• Size of an ArrayList in Java is total number of
elements currently stored in ArrayList.

• To get size of an ArrayList we can call it’s method


size( ) whose prototype is :
• public int size( )

Example:
int sz=cities.size( );
System.out.println(sz); // 3
Retrieving ArrayList Element
• To get an element from the ArrayList we can
Note that we didn’t have to
call it’s get( ) method. type-cast the return value
• It’s prototype is: to String , since we have
• public Object get(int index)
used a type-safe list

• If index is out of range then it throws the


exception IndexOutOfBoundsException.
Example:
String s=cities.get(0);
System.out.println(s); // Bhopal
Replacing ArrayList Element
• To replace an element in the ArrayList we can call
it’s set( ) method.
• It’s prototype is:
• public Object set(int index,Object o)

• It replaces the object at given index with the new


object passed and returns back the replaced object
Example:
cities.set(0,”Indore”);
System.out.println(cities.get(0)); // Indore
Adding Element In Between
• To add an element in between the ArrayList we
can call it’s overloaded version of add( ) method.
• It’s prototype is:
• public void add(int index,Object o)

• It adds the new object at given index shifting the


already present element downwards
Example:
cities.add(1,”Indore”);
System.out.println(cities.get(1)); // Indore
System.out.println(cities.get(2)); // Paris
Checking Index of An Element
• To search an element in the ArrayList we can
call it’s method indexOf( ) method.
• It’s prototype is:
• public int indexOf(Obect)
• If the element is present it returns it’s index
otherwise it returns -1
Example:
System.out.println(cities.indexOf(“Bhopal”)); // 0
System.out.println(cities.indexOf(“Goa”)); // -1
Removing an Element from ArrayList
• There are two ways to remove any elements from
ArrayList in Java.
• We can either remove an element based on
its index or by providing object itself.
• Prototype:
• public Object remove(int)
• public boolean remove(Object)

Example:
cities.remove(“Bhopal”);
System.out.println(cities.indexOf(“Bhopal”)); // -1
Traversing An ArrayList
Many a times we need to traverse on Java ArrayList and
perform some operations on each retrieved item. Following
are 2 ways for this:

Using Regular for loop

for (int i = 0; i < cities.size(); i++){


String s= cities.get(i);
System.out.println(s);
}
Using Enhanced For loop
for(String s: cities){
System.out.println(s);
}
Checking if ArrayList is Empty
• We can use isEmpty() method of Java ArrayList to
check whether ArrayList is empty. isEmpty() method
returns true if this ArrayList contains no elements. We can
also use size() method of List to check if List is empty

boolean result = stringList.isEmpty();

OR

if(stringList.size() == 0)
System.out.println("ArrayList is empty");

Summary Of Benefits
1. Maintains the insertion order of elements

2. Can grow and shrink dynamically

3. Elements can be added or removed from a particular


location

4. Provides methods to manipulate stored objects


Programming Challenge -1
When a student joins the school their information needs to
be recorded.
1. Implement a class that maintains a student record in an
ordered collection
2. When a student joins the school , his
information(Name,RollNo and Grade) should be added
to the record list and when he leaves , the information
should be removed.
3. In the driver class , create some student objects , add
them to the record and display the list .
4. Then remove some students and display the list again.
Programming Challenge -2
Improve the previous code by displaying the
student list in an alphabetical order of their
names
How To Sort The ArrayList ?
• The Java language provides us predefined
sorting functions/methods to sort the elements of
collections like ArrayList.

• Thus we do not have to write our own logic for


sorting these collections.
How To Sort The ArrayList ?
• This is done using a class called “Collections” in
the package java.util which contains a static
method called sort( ) which can sort an ArrayList

• The prototype of the method is:


• public static void sort(List L)

• This method accepts a List as argument and


sorts it’s elements in natural order .
What Is Natural Order?
• Natural order means the default sorting order
which is as follows:

• If the List consists of String elements, it will be sorted


into alphabetical order.

• If it consists of Date elements, it will be sorted into


chronological order.

• If it contains Integers , it will be sorted in numeric


order.

How To Sort The ArrayList ?
• But when we call the sort( ) method of
Collections class and pass it our student list then
it will generate an error.

• Can you guess why ?

• This is because we have not defined any sorting


order for our student objects !!!
Solution
• To solve this problem we will have to supply the
information to Collections class about how to
sort the students list.

• This is done by implementing an interface called


Comparable and overriding it’s method called
compareTo( ) which has the following prototype:
• public int compareTo(Object)
The “LinkedList” class
• LinkedList implements List interface.

• Uses Doubly Linked List internally.

• The LinkedList is not synchronized.

• No initial capacity, capacity/size increases as elements are


added

• Insertion order is preserved

• Good choice when frequent operations are adding and


removing and worst when frequent operation is retrieval
Internal Mechanism Of LinkedList
• A LinkedList is an organized collection of elements called
as nodes where each node contains an element and a
reference to the next element
Adding Elements In The LinkedList
LinkedList <String>cities = new LinkedList<String>();
cities.add(“Bhopal”);
cities.add(“Paris”);
cities.add(“Delhi”);

The above code will create three nodes having “Bhopal” ,


“Paris” and “Delhi” as their contents and references of
three nodes adjusted to point to previous and next nodes

“Bhopal””Paris””Delhi”
Adding Elements In The LinkedList
Now suppose we want to add “New York” at position 2
then we would write

cities.add(1,”New York”);

To make this adjustment , three steps will be done:


a. Creating a new node with “New York”
b. Breaking links of “Paris” and “Delhi”
c. Adjust links of “Paris””NewYork” as well as
“NewYorkDelhi”
“Bhopal””Paris””NewYork””Delhi”
Getting Element From The LinkedList
•To get a particular element from LinkedList we use the
same method called get( ) passing it the index no .

•Example
System.out.println(cities.get(2));// Delhi
Getting Element From The LinkedList
•Although LinkedList provides us a get( ) method , but
when we use it to access a particular element then it
internally traverses the complete list upto the element
required .

•On the other hand if we use ArrayList then directly the


element is accessed based on index no.

•Thus ArrayList supports Random Access , while


Linked List supports Sequential Access
Summary Of Benefits
1. Maintains the insertion order of elements

2. Efficient for adding and removing elements from the


middle of the list

3. Good for sequential access , but not for random access


The Set Interface
1.The Set interface extends the Collection interface.

2.A Set is a Collection that cannot contain duplicate


elements.

3. It does not preserve the insertion order.


Implementation Classes Of Set
There are 2 implementation classes of Set interface:
1- HashSet
2- TreeSet

The HashSet represents a set backed by a hash table


providing constant lookup−time access to unordered
elements.

The TreeSet maintains its elements in an ordered fashion


within a balanced tree.
The HashSet Class
1.This class implements the Set interface

2.It creates a collection that uses a hash table for storage.

3.Hash table stores information by using a mechanism called


hashing.

4.HashSet is not synchronized.

5.It makes no guarantees as to the iteration order of the set.


6. The method used are add( ) , remove( ) ,clear( ) ,size( ) and
contains( ).
How HashSet Works Internally ?
• HashSet internally uses HashMap for storing data.

•This means that when HashSet, add("data") method is


called, add method internally calls HashMap put(key,
value) method.
Internal Code Of HashSet Class ?
public class HashSet implements Set
{
private transient HashMap<E,Object> map;

//Dummy Value to store against key


private static final Object PRESENT = new Object();

public HashSet() {
map = new HashMap<>();
}

public boolean add(Object e) {


return map.put(e, PRESENT)==null;
}
}
How HashSet Works Internally ?
• Once HashMap put( ) method is invoked, it stores the
data(key-value pair) in bucket, by first evaluating
hashcode( ) of key.

•It then identifies exact bucket(array index) and then does


equals( ) comparison of the key to store and the key of
already stored key-value pairs in linked list present in that
bucket.
How HashSet Works Internally ?
What HashMap Does When put( ) Is
Called ?
• It does 2 things:

• When "Key" is already present, then it replaces the old value, with
new value and returns old value.

• When "Key" is not present, then it adds the key-value pair


and returns null.
Example
• Suppose we wrote : hs.add(“Sachin”);
• add ( )method will put it in map as map.put(“Sachin",
DUMMY_VALUE);

• If key “Sachin" is not present in map, then hashmap will add


Sachin as key and value as DUMMY_VALUE and will return null,
which is indication for hashset add method that key “Sachin" is not
present in map previously and has been added.

• Hashset add( ) method checks that if HashMap put( ) method


returned null it means supplied data is entered for first time and add
method returns true
Example
• But If key “Sachin" is already present in map, then
hashmap will return old value stored against key “Sachin"
which will always be DUMMY_VALUE because value is
always fixed in case of hashset.

• So when hashmap returns other than null, then this is


indication for add method of hashset that there is already
key “Sachin" present and need to return false.
import java.util.*;
public class HashSetDemo {
public static void main(String args[]) {
HashSet HSet = new HashSet();
HSet.add("C");
HSet.add("A");
HSet.add("B");
HSet.add("E");
HSet.add("F");
HSet.add("D");
System.out.println("The HashSet elements are: " + HSet);
}
}
Output:
The HashSet elements are: [D, E, F, A, B, C]
import java.util.*;
public class HashsetDemo {
public static void main(String[] args) {
HashSet <String> hs=new HashSet<String>();
hs.add("Amit");
hs.add("Sumit");
hs.add("Amit");
System.out.println(hs);

}
}
Output:
[Amit, Sumit]
class Student
{
private String name;
public Student(String name){ public class HashSetDemo{
this.name=name; public static void main(String[] args) {
} HashSet <Student> hs;
hs=new HashSet<Student>();
Student s1=new Student("Amit");
public String toString(){ Student s2=new Student("Sumit");
return name; Student s3=new Student("Amit");
} hs.add(s1);
hs.add(s2);
hs.add(s3);
} System.out.println(hs);
}
}
Output:
[Amit , Sumit , Amit]
Why Did Duplicates Were Not Removed ?
• This is because when we add any object to HashSet ,
then java locates it in the internal HashMap using it’s
hashCode( ) and if finds that the hashCode( ) of the new
object is unique , then creates an entry in the HashMap
and adds the object.

• Now , since we have not overridden hashCode( ) method


in our Student class so we got two student objects having
the same name.
What Other Method We Should Override
With HashCode?
• We should also override equals( ) alongwith hashCode( )
because the HashMap which holds the data for HashSet
also calls equals( ) along-with hashCode( ) to match the
actual value.
Programming Challenge-3
A BookStore contains a collection Book where each Book
has a name , an author and price. Write
program which does the following:
1. The BookStore wants to maintain a unique collection of
the Books i.e. it should not accept a Book if it is already
present

2. Retrieval of Book should be in an efficient way.


The TreeSet class
1. This class implements the Set interface.

2. The TreeSet class is useful when we need to extract


elements from a collection in a sorted manner.

3. It stores its elements in a tree and they are


automatically arranged in a sorted order.

4. TreeSet is not synchronized.


Program
import java.util.*;
public class TreeSetDemo {
public static void main(String args[]) {
TreeSet ts = new TreeSet();
ts.add("C");
ts.add("A");
ts.add("B");
ts.add("E");
ts.add("F");
ts.add("D");
System.out.println(ts);
}
}
Output:
[A, B, C, D, E, F]
What is an Iterator ?
1.The List and Set collections provide iterators, which are
objects that allow going over all the elements of a collection
in sequence
2.To access a collection through an iterator, we have to
obtain an iterator.
3. The java.util.Iterator interface provides for one-way
traversal
3.Each of the collection classes provides an iterator( )
method that returns an Iterator object to the start of the
collection.
4.By using this iterator object, we can access each element
in the collection, one element at a time
How to use an Iterator ?
In general, to use an iterator to cycle through the contents
of a collection, follow these steps:

1. Obtain an iterator to the start of the collection by calling


the collection's iterator( )
2. Set up a loop that makes a call to hasNext( ). Have the
loop iterate as long as hasNext( ) returns true.
3. Within the loop, obtain each element by calling next( ).
Traversing a TreeSet
import java.util.*;
public class SetDemo {
public static void main(String[] args) {
Set st = new TreeSet();
st.add("Gyan");
st.add("Rohit");
st.add("Anand");
st.add("Arunesh");
Iterator itr = st.iterator();
while (itr.hasNext()) {
String str = (String) itr.next();
System.out.println("Name :" + str);
}
}
}
Output
Name :Anand

Name :Arunesh

Name :Gyan

Name :Rohit
HashSet v/s TreeSet
1.HashSet is much faster than TreeSet as it has a
constant-time for most operations like add, remove and
contains but offers no ordering guarantees like TreeSet.

2. TreeSet offers a few handy methods to deal with the


ordered set like first(), last(), etc which are not present in
HashSet

3. None of these classes are synchronized. That is if


multiple threads access a set concurrently, and at least one
of the threads modifies the set, it must be synchronized
externally.
Adding Custom Objects To TreeSet
•Suppose we want to create a TreeSet of Book object
and we want to get the output in descending order of
price

•Now , if we write :
TreeSet<Book> ts=new TreeSet<Book>( );
Book b1=new Book("Let Us C","Kanetkar",350);
Book b2=new Book("Java Certification","Kathy",650);
Book b3=new Book("Mastering C++","Venugopal",500);
ts.add(b1);
ts.add(b2);
ts.add(b3);
•Then java will throw a ClassCastException.
Adding Custom Objects To TreeSet
• This is because for any object which we add to the
TreeSet created using default constructor , then 2
conditions must be compulsorily satisfied:
1 The objects added must be homogeneous
2 The objects must be comparable i.e. the class must
implement the java.lang.Comparable interface.

In our case since Book has not implemented the


Comparable interface, a ClassCastException arised.

So to solve the above exception , we must implement


the Comparable interface in our Book class
How TreeSet Uses compareTo( ) ?

Following are the steps it follows:

1. For the first object no compareTo( ) method is called

2. For the second object it calls the compareTo( ) method


with the current object as calling object and the existing
object as the argument.

3. If positive value is returned then current object goes


towards right else it goes towards left.
The Map Interface
• It is not child interface of Collection interface but has
methods similar to Collection
• A Map is an object that maps keys to values.
The Map Interface

• Mainly used for look ups

• Map cannot contain duplicate keys.

• Each key can map to at most one value.


The Map Interface
• The Map interface includes methods for basic operations
such as put() , get(), remove(), containsKey(),
containsValue(), size() and isEmpty().

• It also provides methods for collection views of it’s


contents like keySet(),values() and entrySet()
Implementation Classes Of Map
Implementation Classes
The Collections Framework provides 2 very important Map
implementation:

1 - HashMap
2 - TreeMap

HashMap:
The HashMap is a class which is used to perform some basic
operations such as inserting, deleting, and locating elements in a
Map . It works with the Iterators.
TreeMap:
The TreeMap implementation is useful when we need to traverse
the keys from a collection in a sorted manner. The elements
added to a TreeMap must be sortable in order to work properly.
The HashMap class

• HashMap class extends AbstractMap and


implements Map interface.
The HashMap class

• Internally uses HashTable to store the data.

• HashMap methods are unsynchornized .

• It allows null key and null values


The HashMap class

• It is not an ordered collection which means it does not


return the keys and values in the same order in which
they have been inserted into the HashMap.

• It neither does any kind of sorting to the stored keys and


Values.

• Ensures retrieval of the object on constant time i.e. O(1)


Program
import java.util.*;
class MapDemo {
public static void main(String[] args) {
Map mp = new HashMap();
mp.put("Sachin", 9826086245L);
mp.put("Paramjeet",9826686245L );
mp.put("Amit", 9700674321L);
mp.put("Rahul", 7812096543L);
System.out.println(mp);
System.out.println(mp.get("Sachin"));
}
}
Output:
{Rahul=7812096543, Sachin=9826086245, Amit=9700674321,
Paramjeet=9826686245}
Sachin:9826086245
How values are stored in Map ?
1.Each element is a map has a key and value.
2.Each key-value pair is saved in a java.util.Map.Entry
object.
3.A set of these map entries can be obtained by calling a
map's entrySet( ) method.
4.Iterating over a map is done by iterating over this set.
How HashMap Works Internally ?

• HashMap works on the principal of hashing.

• It is a data structure which allows us to store object and


retrieve it in constant time O(1) provided we know the key.

• HashMap maintains an array of buckets. Each bucket is


a linkedlist of key value pairs encapsulated as Entry
objects
How HashMap Works Internally ?

• This array of buckets is called table. Each node of the


linked list is an instance of a private class called Entry.

• When we call put( ) method, hashcode() method of key


object is called so that hash function of map can find a
bucket location to store value object
How put( ) methods works ?

• First of all, key object is checked for null. If key is null,


value is stored in table[0] position. Because hash code
for null is always 0.

• Then on next step, a hash value is calculated using key’s


hash code by calling its hashCode() method.
How put( ) methods works ?

• Then on next step, another hash( ) function is called on


the hashcode value. Why ?

• Because JDK designers well assumed that there might be


some poorly written hashCode() functions that can return
very high or low hash code value.

• To solve this issue, they introduced


another hash()function, and passed the object’s hash
code to this hash() function to bring hash value in range
of array index size.
How put( ) methods works ?

• Now indexFor(hash, table.length) function is called to


calculate exact index position for storing the Entry object.

• Now, as we know that two unequal objects can have


same hash code value, so how two different objects will
be stored in same array location [called bucket] ?

• Answer is LinkedList.
How put( ) methods works ?

• Entry objects are stored in LinkedList form.

• When an Entry object needs to be stored in particular


index, HashMap checks whether there is already an
entry?? If there is no entry already present, Entry object is
stored in this location.
How put( ) methods works ?

• If there is already an object sitting on calculated index, its


next attribute is checked.

• If it is null, and current Entry object becomes next node in


LinkedList. If next variable is not null, procedure is
followed until next is evaluated as null.
How put( ) methods works ?

• If we add the another value object with same key as


entered before , it replaces the old value.

• How it is done?
How put( ) methods works ?

• Actually after determining the index position of Entry


object, while iterating over LinkedList on calculated
index, HashMap calls equals( ) method on key object for
each Entry object.

• All these Entry objects in LinkedList will have similar hash


code but equals() method will test for true equality.

• If key.equals(k) will be true then both keys are treated as


same key object. This will cause the replacing of value
object inside Entry object only.
How put( ) methods works ?

• But the hashcode which we get from the hashCode( )


method cannot be used as an index in the bucket.

• To solve this issue, HashMap uses another function


called hash() function, and passes the object’s hash
code to this hash() function to bring hash value in range
of array index size.
How get( ) methods works ?

• The way key uniqueness is determined in put() method ,


same logic is applied in get() method also.

• The moment HashMap identify exact match for the key


object passed as argument, it simply returns the value
object stored in current Entry object.
Program
import java.util.*;
public class HashMapDemo {
public static void main(String args[]) {
HashMap hm = new HashMap();
hm.put(1, "Gyan");
hm.put(2, "Ankit");
hm.put(3, "Arun");
hm.put(4, "Anand");
hm.put(5, "Ram");
Set set = hm.entrySet();
Iterator i = set.iterator();
while (i.hasNext()) {
Map.Entry me = (Map.Entry) i.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
System.out.println();
}
}
Ouput
1: Gyan
2: Ankit
3: Arun
4: Anand
5: Ram
Checking whether a value exists or not
To get the Value from HashMap object we use the method:
boolean containsValue(value)

This method returns true if list contains the specified Value


otherwise returns false.
Program
import java.util.*;
public class HashMapDemo{
public static void main(String args[]) {
HashMap hm = new HashMap();
hm.put(1, "Gyan");
hm.put(2, "Ankit");
hm.put(3, "Arun");
hm.put(4, "Anand");
hm.put(5, "Ram");
boolean bool = hm.containsValue("Gyan");
System.out.println(“Does Gyan is exists in HashMap : "
+ bool);
}
}
Output:
Does Gyan is exists in HashMap : true
Using remove( ) and size( )
To get total number of elements in a HashMap we use the
method:
public int size()

To remove a particular key from the HashMap we use the


method:
public Object remove(key)
This method removes the specified entry from the
HashMap whose key is passed as argument and returns
the deleted value
import java.util.*;
public class HashMapDemo {
public static void main(String args[]) {
HashMap hm = new HashMap();
hm.put(1, "Gyan");
hm.put(2, "Ankit");
hm.put(3, "Arun");
hm.put(4, "Anand");
hm.put(5, "Ram");
System.out.println("The size of HashMap is : " + hm.size());
Object obj = hm.remove(3);
System.out.println("The value of removed key is : " + obj);
System.out.println("The size of HashMap after alteration is : "
+ hm.size());

}
}
Output
Output:
The size of HashMap is : 5
The value of removed key is : Arun
The size of HashMap after alteration is : 4
The TreeMap class
1.The TreeMap class implements the Map interface by
using a tree.

2. A TreeMap provides an efficient means of storing


key/value pairs in sorted order,and allows rapid retrieval.

3.Unlike a hash map, a tree map guarantees that its


elements will be sorted in ascending key order.(key, value)
pairs are ordered on the key.
import java.util.*;
class TreeMapDemo {
public static void main(String args[]) {
TreeMap tm = new TreeMap();
tm.put("Rajesh", new Integer(30000));
tm.put("Chetan", new Integer(12000));
tm.put("Atul", new Integer(16000));
tm.put("Amit", new Integer(21000));
tm.put("Ram", new Integer(24000));
Set set = tm.entrySet();
Iterator i = set.iterator();
while(i.hasNext()) {
Map.Entry me = (Map.Entry)i.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
System.out.println();
int balance = ((Integer)tm.get("Atul")).intValue();
tm.put("Atul", new Integer(balance + 1000));
System.out.println("Atul's new balance: " +
tm.get("Atul"));
}
}
Output
Amit: 21000
Atul: 16000
Chetan: 12000
Rajesh: 30000
Ram: 24000
Atul's new balance: 17000
HashMap v/s TreeMap
1. HashMap allows null as both keys and values.
2. HashMap is useful when we need to access the map
without cosidering how they are added to the map
(means, unordered lookup of values using their keys).
3. HashMap doesn’t allow duplicated entries.
4. TreeMap the elements are stored in a tree.
5. TreeMap allows us to retrieve the elements in some
sorted order .
6. So we can say that TreeMap is slower than HashMap

You might also like