Collections-Day 6
Collections-Day 6
• 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( )
• int size( )
Collection c=hm.values();
Important Methods Of Map
• Set keySet( )
Set s2=hm.entrySet();
Important Methods Of Entry
• Object getKey( )
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
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(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
Name Phone
Sachin 9826086245
Aftaab 7992202926
Arif 8982585147
Mohnish 8962336876
Adding Data In 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:
boolean containsValue(value)
This method returns true if list contains the specified Value
otherwise returns false.
boolean containsKey(value)
}
}
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);
}
}
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()
}
}
Output
Output:
The size of HashMap is : 4
The size of HashMap after alteration is : 3
The TreeMap class
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;
*/
HashMap<Integer,Account>accounts=bank.getAllAccounts();
Iterator it = accounts.entrySet().iterator();
while(it.hasNext()){
System.out.println(it.next());
}
}
}
o/p-