0% found this document useful (0 votes)
8 views51 pages

Collections-Day 6

Collection
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views51 pages

Collections-Day 6

Collection
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 51

COLLECTIONS

(An easy way to manage


Objects)
The Map Interface
• It is not child interface of Collection interface but has
methods similar to Collection
• A Map is an object that stores data in pairs , called key-
value pair
How values are stored in Map ?
1.The keys in a Map have to be unique .while allows
repetation of values.

2.Each key-value pair is saved in the map is saved as an


object of type Entry

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.


Important Methods Of Map
• Object put(Object k, Object v)

1. Puts an entry in the invoking map, overwriting any


previous value associated with the key.

2. The key and value are k and v, respectively.

3. Returns null if the key did not already exist , otherwise


it returns the previous value linked to the key
Important Methods Of Map
• Object get(Object k)

1. Returns the value associated with the key k

2. If the key is not found , it returns null.


Important Methods Of Map
• void clear( )

1. Removes all key/value pairs from the invoking map.


Important Methods Of Map
• boolean containsKey(Object k)
1. Returns true if the invoking map contains k as a key.
2. Otherwise, returns false.

• boolean containsValue(Object v)
1. Returns true if the map contains v as a value.
2. Otherwise, returns false
Important Methods Of Map
• boolean isEmpty( )

1. Returns true if the invoking map is empty.


2. Otherwise, returns false.

• int size( )

1. Returns the number of key/value pairs in the map.


Important Methods Of Map
• Object remove(Object k)

1. Removes the entry whose key equals k

2. Returns the previous value associated with the specified


key,

3. Otherwise it returns null if there was no mapping for


the key
Important Methods Of Map
• Collection values( )

1. Returns a Collection containing the values in the map.


2. And we can store it In Collection only

Collection c=hm.values();
Important Methods Of Map
• Set keySet( )

1. Returns a Set that contains the keys in the invoking


map.
2. For storing key only
Set s1 =hm.keySet();
Important Methods Of Map
• Set entrySet( )

1. Returns a Set that contains the entries in the map.

2. The set contains objects of type Map.Entry.

For return key and values

Set s2=hm.entrySet();
Important Methods Of Entry
• Object getKey( )

1. Returns the key corresponding to this Entry object


Important Methods Of Entry
• Object getValue( )

1. Returns the value corresponding to this Entry object


Important Methods Of Entry
• Object setValue(Object)

1. Replaces the old value corresponding to this entry with


the specified value
2. Returns the old value
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. No
indexing
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.
No indexing
The HashMap class

• Internally uses HashTable to store the data.

• Stores data as key-value pairs

• It contains only unique elements.

• It is not an ordered collection.


The HashMap class

• 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)


The HashMap Constructors
• HashMap( )
This constructs an empty HashMap with the default initial capacity
(16) and the default load factor (0.75).

Load factor means 16 ka 75% size full hone par apni size increase
karega

• HashMap(int initialCapacity)
Constructs an empty HashMap with the specified initial
capacity and the default load factor (0.75).
The HashMap Constructors

• HashMap(int initalCapacity,float loadFactor )


Constructs an empty HashMap with the specified initial
capacity and load factor.

• HashMap(Map m)
Constructs a new HashMap with the same mappings as
the specified Map. // it converts TreeMap into HashMap
Exercise 9
WAP to store the Names and Phone Numbers of following

members of TEAM SCA . Now retrieve these values and


display them

Name Phone
Sachin 9826086245
Aftaab 7992202926
Arif 8982585147
Mohnish 8962336876
Adding Data In HashMap

HashMap<String,Long> teamSca = new HashMap<>();

teamSca.put("Sachin", 9826086245L);

teamSca.put("Aftaab",7992202926L );

teamSca.put("Arif", 8982585147L);

teamSca.put("Mohnish", 8962336876L);
Retrieving Data From HashMap
• Retrieval of data from HashSet can be done in 4 ways:

• Retrieving all values together

• Retrieving only keys

• Retrieving only values

• Retrieving key-value pairs


Retrieving All Values Together
For this we simply have to pass the name of HashSet
reference to the method println()
Example:
HashMap<String,Long> teamSca = new HashMap<>();
teamSca.put("Sachin", 9826086245L);
teamSca.put("Aftaab",7992202926L );
teamSca.put("Arif", 8982585147L);
teamSca.put("Mohnish", 8962336876L);
System.out.println(teamSca);
Output:
{Mohnish=8962336876, Aftaab=7992202926, Sachin=9826086245,
Arif=8982585147}

Note- HashMap { } me ans deta hai and = by default aata hai


Retrieving Only The Keys
For this we have to do 2 things:
1. Call the method keySet() which returns a Set of keys of the HashMap
2. Use an Iterator over this Set
Example:
HashMap<String,Long> teamSca = new HashMap<>();
.......
Set<String> names=teamSca.keySet();
Iterator <String> it=names.iterator();
while(it.hasNext())
{
String str=it.next();
System.out.println(str);
}
Output:
Mohnish
Aftaab
Sachin
Retrieving Only The Values
For this we have to do 2 things:
1. Call the method values() which returns a Collection of values of the
HashMap
2. Use an Iterator over this Collection
Example:
HashMap<String,Long> teamSca = new HashMap<>();
.......
Collection <Long> mobNo=teamSca.values();
Iterator <Long> phNo=mobNo.iterator();
while(phNo.hasNext())
{
Long p = phNo.next();
System.out.println(p);
}
Output:
8962336876
7992202926
9826086245
Retrieving Key-Value Pairs
For this we have to do 2 things:
1. Call the method entrySet( ) which returns a Set of all the data
in the HashMap

2. Each element in this Set is an object of type Entry

3. Entry is an inner interface of Map and has 2 methods called


getKey() and getValue()

4. So we will have to get an Iterator over this Entry


Retrieving Key-Value Pairs
Example:
HashMap<String,Long> teamSca = new HashMap<>();
.......
Set <Map.Entry<String,Long>> members=teamSca.entrySet();
Iterator<Map.Entry<String,long>> it=e.iterator();
while(it.hasNext())
{
Map.Entry<String,Long> et=it.next();
System.out.println(et.getKey()+","+et.getValue());
}
Output:
Mohnish,8962336876,
Aftaab,7992202926,
Sachin,9826086245
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.

• To get the Key from HashMap object we use the method:

boolean containsKey(value)

This method returns true if list contains the specified Key


otherwise returns false.
Program
import java.util.*;
public class HashMapDemo{
public static void main(String args[]) {
HashMap<String,Long> teamSca = new HashMap<>();
teamSca.put("Sachin", 9826086245L);
teamSca.put("Aftaab",7992202926L );
teamSca.put("Arif", 8982585147L);
teamSca.put("Mohnish", 8962336876L);

boolean bool = teamSca.containsKey(“Sachin");


System.out.println(“Does Sachin is exists in HashMap : " +
bool);

}
}
Output:
Does Sachin is exists in HashMap : true
Program
import java.util.*;
public class HashMapDemo{
public static void main(String args[]) {
HashMap<String,Long> teamSca = new HashMap<>();
teamSca.put("Sachin", 9826086245L);
teamSca.put("Aftaab",7992202926L );
teamSca.put("Arif", 8982585147L);
teamSca.put("Mohnish", 8962336876L);

boolean bool = teamSca.containsValue(“Sachin");


System.out.println(“Does Sachin is exists in HashMap : " +
bool);

}
}
Output:
Does Sachin is exists in HashMap : false
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<String,Long> teamSca = new HashMap<>();
teamSca.put("Sachin", 9826086245L);
teamSca.put("Aftaab",7992202926L );
teamSca.put("Arif", 8982585147L);
teamSca.put("Mohnish", 8962336876L);
System.out.println("The size of HashMap is : " + hm.size());
hm.remove(“Arif");
System.out.println("The size of HashMap after alteration is : "
+ hm.size());

}
}
Output
Output:
The size of HashMap is : 4
The size of HashMap after alteration is : 3
The TreeMap class

• TreeMap class implements NavigableMap , SortedMap


and Map interfaces.
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

3.Sort in basis of Key.

3. Doesn’t store duplicates


Example
import java.util.*;
class TreeMapDemo {
public static void main(String args[]) {
TreeMap<String,Long> teamSca = new TreeMap<>();
teamSca.put("Sachin", 9826086245L);
teamSca.put("Aftaab",7992202926L );
teamSca.put("Arif", 8982585147L);
teamSca.put("Mohnish", 8962336876L);
System.out.println(teamSca);
}
}
Output
{Aftaab=7992202926, Arif=8982585147,
Mohnish=8962336876, Sachin=9826086245}
Example
import java.util.*;
class TreeMapDemo {
public static void main(String args[]) {
TreeMap<String,Long> teamSca = new TreeMap<>();
teamSca.put("Sachin", 9826086245L);
teamSca.put("Aftaab",7992202926L );
teamSca.put("Arif", 8982585147L);
teamSca.put("Mohnish", 8962336876L);
Set e=teamSca.entrySet();
Iterator it=e.iterator(); // if here not do tpecast
while(it.hasNext())
{
Entry et=(Map.Entry)it.next(); //then here type cast
System.out.println(et.getKey()+","+et.getValue());
}
}
}
Output
Aftaab,7992202926,
Arif,8982585147
Mohnish,8962336876
Sachin,9826086245
Exercise 10
A Bank maintains bank account of it’s users in the
database. When you visit the bank and tell your account
number to the teller , he fetches your account details.

1. Create a collection and maintain bank accounts in that.

2. There should be a single entry for one account


number

3. We should be able to fetch the account details when


an account number is supplied to the collection.
The program should have 3 classes:
1. Account : should contain 3 data members called accountNumber, name and
balance . Also provide appropriate constructor and other important methods

2. Bank: should contain a HashMap of Account . Also provide 5 methods called


:
1. addAccount( )
2. getAccount()
3. removeAccount()
4. getCount()
5. getAllAccounts( )

3. UseBank: This will be our driver class . It will contain code to do the following:
1. Create 4 Account objects and add them to the Bank .
2. Display their details.
3. Now fetch the details of a particular account by passing it’s account number
4. Remove an account by passing it’s account number
5. Display total number of Accounts
import java.util.*;

class Account{
private Integer accountId;
private String name;
private Double balance;

public Account(Integer accountId,String name,Double balance){


this.accountId=accountId;
this.name=name;
this.balance=balance;
}
public Integer getAccountId(){
return accountId;
}

/** ydi bad me change karna ho

public void setAccountId(Integer accountId){


this.accountId=accountId;
}
public String getName(){
return name;
}
public void setName(String name){
this.name=name;
}
public Double getBalance(){
return balance;
}
public void setBalance(Double balance){
this.balance=balance;
}

*/

public String toString(){


return "Account{"+ "AccountId="+accountId+",
name="+name+", balance="+balance+"}";
}
}
class Bank{

private HashMap<Integer,Account> accounts=null;


public Bank(){
accounts=new HashMap<>();
}

public boolean addAccount(Account obj){


if(accounts.put(obj.getAccountId() , obj)==null)
return true;
else
return false;
}

public Account getAccount(Integer id){


return accounts.get(id);
}
public boolean removeAccount(Integer id){
if(accounts.remove(id)==null)
return false;
else
return true;
}
public int getCount(){
return accounts.size();
}
public HashMap<Integer,Account>getAllAccounts(){
return accounts;
}

public class UseBankTreeMap {


public static void main(String[] args) {
Account obj1=new Account(1001,"Anil",50000.0);
Account obj2=new Account(1002,"Ravi",34000.0);
Account obj3=new Account(1003,"Manish",65000.0);
Account obj4=new Account(1004,"Ajit",45000.0);

Bank bank=new Bank();

System.out.println("Account id :"+obj1.getAccountId()+" added


:"+bank.addAccount(obj1));
System.out.println("Account id :"+obj2.getAccountId()+" added
:"+bank.addAccount(obj2));
System.out.println("Account id :"+obj3.getAccountId()+"
added :"+bank.addAccount(obj3));
System.out.println("Account id :"+obj4.getAccountId()+"
added :"+bank.addAccount(obj4));
System.out.println("Account id :"+obj1.getAccountId()+"
added :"+bank.addAccount(obj1));

System.out.println("Details of Account : 1004 ->


"+bank.getAccount(1004));
System.out.println("Removing Account id :1004 ->
"+bank.removeAccount(1004));
System.out.println("Details of Account : 1004 ->
"+bank.getAccount(1004));

HashMap<Integer,Account>accounts=bank.getAllAccounts();
Iterator it = accounts.entrySet().iterator();
while(it.hasNext()){
System.out.println(it.next());
}
}
}
o/p-

Account id :1001 added :true


Account id :1002 added :true
Account id :1003 added :true
Account id :1004 added :true
Account id :1001 added :false
Details of Account : 1004 -> Account{AccountId=1004, name=Ajit, balance=45000.0}
Removing Account id :1004 -> true
Details of Account : 1004 -> null
1001=Account{AccountId=1001, name=Anil, balance=50000.0}
1002=Account{AccountId=1002, name=Ravi, balance=34000.0}
1003=Account{AccountId=1003, name=Manish, balance=65000.0}

• It is not compulsory that o/p cames in sorted order


Exercise 11
Make changes in the Bank Application so that whenever we
display the records , they always get displayed in sorted
order of account id

use TreeMap in place of HashMap


HashMap v/s TreeMap
1. HashMap is useful when we need to access the map
without considering how they are added to the map
(means, unordered lookup of values using their keys).

2. HashMap doesn’t allow duplicated entries.

3. TreeMap stores the elements in a tree.

4. TreeMap allows us to retrieve the elements in some


sorted order .

5. So we can say that TreeMap is slower than HashMap

You might also like