HashMap :
·
HashMap is a predefined class in Java.
·
It is used to store values in the form of
key-value pairs.
·
HashMap implements the Map interface in Java.
·
HashMap does not allow duplicate keys. If a
duplicate key is inserted, the old value associated with the key is replaced by
the new value.
·
HashMap allows one null key and multiple null
values.
·
Common Methods:
- put(K
key, V value): Inserts the specified key-value pair into the map.
- get(Object
key): Returns the value associated with the specified key.
- remove(Object
key): Removes the key-value pair for the specified key.
- containsKey(Object
key): Checks if the map contains the specified key.
- size():
Returns the number of key-value pairs in the map.
package CollectionFrameBasics;
import java.util.HashMap;
public class HashMapBasics {
public
static void main(String[] args) {
//
create objHashMap of String, String , K,V -
HashMap<String,
String> hm = new HashMap<String, String>();
//
check hashmap is empty
boolean
isEmpty = hm.isEmpty();
//
System.out.println("isEmpty
="+isEmpty);
// /isEmpty true
System.out.println("hashmap="+
hm);
//
hashmap={}
//
inserting some values Key- val
// A
-Apple
// B
-Ball
// C
-Cat
// D
-Dog
hm.put("A",
"Apple");
hm.put("B",
"Ball");
hm.put("C",
"Cat");
hm.put("D",
"Dog");
System.out.println("hash
map="+ hm);
// hash
map=
//
check hashmap contains given key name -
B is there or not
boolean containsKeyB = hm.containsKey("B");
// true
System.out.println("containsKeyB
="+containsKeyB);
// true
//
Check hashmap contains given Key = P
boolean
containsKeyP = hm.containsKey("P");
// false
// false as 'P' is not there
in hashamp
System.out.println("containsKeyP
="+containsKeyP);
// false
//
count values in hashmap
int
hmCount= hm.size();
// 4
System.out.println("cnt
="+ hmCount);// 4
// get value of given key -B
String
valB = hm.get("B");
// Ball
//
// get value from based on key name
System.out.println("valB="+valB);//
Ball
//
get P' value
String valP =hm.get("P");
//
null
// if given Key i.e "P" is not there
in hashmap, it returns null value
// get value from based on key name
System.out.println("valP="+valP);
// null
if given key name is not there in hash map, it returns null value
//
Remove given key name 'C"
hm.remove("C");
// {A=Apple, B=Ball, C=Cat,
D=Dog}
//
{A=Apple, B=Ball, D=Dog}
System.out.println("after
Removing C,hash map="+ hm);
//after
Removing C,hash map=/ {A=Apple, B=Ball, D=Dog}
//
remove P
hm.remove("P");
// {A=Apple, B=Ball, D=Dog}
System.out.println("after
Removing P,hash map="+ hm);
//
aftwr Removing P,hash map={A=Apple, B=Ball, D=Dog, E=Egg}
// no error here
//
clear() - to remove all values in hashmap
hm.clear();
System.out.println("after
Removing all values,hash map="+ hm);
// after Removing all values,hash map={}
//
HW Check hash map contains 'Apple'
//HW Check hash map contains 'Parrot'
}
}
o/p:
isEmpty =true
hashmap={}
hash map={A=Apple, B=Ball, C=Cat,
D=Dog}
containsKeyB =true
containsKeyP =false
cnt =4
valB=Ball
valP=null
after Removing C,hash
map={A=Apple, B=Ball, D=Dog}
after Removing P,hash map={A=Apple,
B=Ball, D=Dog}
aftwr Removing all vlaues,hash
map={}
get all key
names & values from hashmap:
package CollectionFrameBasics;
import java.util.Collection;
import java.util.HashMap;
import java.util.Set;
public class HashMapBasicsGetKeysValues
{
public
static void main(String[] args) {
//Create
obj for HashMap class -
HashMap<String,
String > hm = new HashMap<String, String >();
// add some key, vals
hm.put("A",
"Apple");
hm.put("B",
"Ball");
hm.put("D",
"Dog");
hm.put("C",
"Cat");
//
get all key names from hashmap
Set<String>
s = hm.keySet();
// get values from set obj
//1 for loop with indexno - not possible
// s.get(0);// The
method get(int) is undefined for the type Set<String>
//2
using for each loop in set
for(String
eachVal:s)
{
// gets
each val from set interface and sstore
the val into variable i.e eachVal
System.out.println("get
all keys from hashmap using for each loop:"+eachVal);
}
// get all keys from hashmap
using for each loop:A
// get all keys from
hashmap using for each loop:B
// get all keys from
hashmap using for each loop:C
// get all keys from
hashmap using for each loop:D
//HW
3 iterator ()
// hm.iterator();// we dont have iterator() for hashmap class
//
iterator() is defined for arraylist and
hashset()
//
to get val from set using itertaor
System.out.println("Get
all keys from set usig iterator()=");
// Get all keys from set
usig iterator()=A
// Get
all keys from set usig iterator()=B
// Get
all keys from set usig iterator()=C
// Get
all keys from set usig iterator()=D
//
4 listIterator() we cannot get / iterate
values from set interface ( not
possible)
// s.listIterator();//
CE: The method listIterator() is undefined for the type Set<String>
//
get all values from hash map
Collection<String>
col = hm.values();
//
Collection is predefined interface -
// Can be used to store group of value / obj's/
ele's
//
import java.util pkg
// can be used to get all values
from hashmap and store into
Collection<String> refer var
//
i.e col
// 4 ways
//
1. for loop with index no -- not possisble
// col.get(0);
//
2 HW
get values from collection obj
using for each loop
//3
.HW get values from collection obj using iterator();
//
clone/Copy the hashmap
Object
oref = hm.clone();
// to copy all keys , values pair
into Object class ref var
System.out.println("oref="+
oref);
// oref={A=Apple, B=Ball, C=Cat,
D=Dog}
//
HW
System.out.println("Before
Removing apple from hm="+ hm);
// remove("A", "Apple");
hm.remove("A","Apple");
// {A=Apple, B=Ball, C=Cat, D=Dog}
//{ B=Ball, C=Cat, D=Dog}
System.out.println("after
Removing Apple from hm="+ hm);
//
after Removing Apple from hm={B=Ball, C=Cat, D=Dog}
//remove("A",
"Ant");
hm.remove("A",
"Ant");
System.out.println("after
Removing 'A' from hm="+ hm);
// after Removing 'A' from hm={B=Ball, C=Cat,
D=Dog}
//
we can insert 1 null key and multiple null values
hm.put(null,
null);
hm.put("E",
null);
System.out.println("hm="+
hm);
// insert where null key is there - insert new value z
hm.put(null,
"Z");
System.out.println("hm="+
hm);
}
}
o//p:
get all keys from hashmap using
for each loop:A
get all keys from hashmap using
for each loop:B
get all keys from hashmap using
for each loop:C
get all keys from hashmap using
for each loop:D
Get all keys from set usig
iterator()=
oref={A=Apple, B=Ball, C=Cat,
D=Dog}
Before Removing apple from
hm={A=Apple, B=Ball, C=Cat, D=Dog}
after Removing Apple from
hm={B=Ball, C=Cat, D=Dog}
after Removing 'A' from
hm={B=Ball, C=Cat, D=Dog}
hm={null=null, B=Ball, C=Cat,
D=Dog, E=null}
hm={null=Z, B=Ball, C=Cat, D=Dog,
E=null}
HashTable:
·
HashTable
is predefined Class in java.
·
HashTable can be used to store values in the
form key and value pair.
·
HashTable
implements the Map interface.
·
No null Keys or Values: Unlike HashMap, Hashtable
does not allow null keys or values. Any attempt to insert null as a key or
value will result in a NullPointerException.
·
Synchronized: Hashtable is synchronized, meaning
it is thread-safe. This makes it suitable for use in multi-threaded
environments where multiple threads may need to access or modify the data
concurrently.
·
Hashtable is generally slower than HashMap due
to synchronization overhead.
package CollectionFrameBasics;
import java.util.Hashtable;
public class HashTableBasics1 {
public
static void main(String[] args) {
//
create hashtable and store key as
Character and values as String
Hashtable<Character,
String> ht = new Hashtable<Character, String>();
// Hashtable<char,
String > ht = new Hashtable<char, String>();
// All Collection frame work classes-- can handle only classes but not primtive
// so dont store primitve data types(int,
float,char.. etc ) in collection obj -
// instead of data type -- we have to use
wrappper clases Integer, Float, Character
//
add character , String values into Hash table
// inserting some values Key- val
// A
-Apple
// B
-Ball
// C
-Cat
// D
-Dog
ht.put('A',
"Apple");
ht.put('B',
"Ball");
ht.put('C',
"Cat");
ht.put('D',
"Dog");
// ht.put("A",
"Appple");// We cann not insert String val "A" into
key
///
Check We can pass String value in Key
//Error
: dont pass string value in key
// as we defined in hashtable key as Character
//
so we can store/insert Character only into Key... but not string, int no, float
no..etc
System.out.println("hash
table-="+ ht);
//
hash table = {A=Apple, D=Dog, C=Cat, B=Ball}
// we cannot insert null key, null value in ht
// ht.put(null, null);
//
// Exception in thread
"main" java.lang.NullPointerException: Cannot invoke "Object.hashCode()"
because "key" is null
// at
java.base/java.util.Hashtable.put(Hashtable.java:481)
// at
CollectionFrameWorkBasics.HashTableBasics1.main(HashTableBasics1.java:34)
//
if we insert null val into hashtable
System.out.println("ht="+
ht);
// Exception in thread "main"
java.lang.NullPointerException
// at
java.base/java.util.Hashtable.put(Hashtable.java:476)
// at
CollectionFrameWorkBasics.HashTableBasics1.main(HashTableBasics1.java:42)
// HW
Repeat all methods from hashmap in hashtable also
//
HW Remove 'A' from hash table
//HW
Remove 'P' from ht
//
HW remove all from ht
//HW check ht contains B or not
//
HW check ht contains 'T'
//
Hw get all key name from hashtable
//HW
get all values from hash table
//
HW count of hash table
}
}
FAQ: Difference Between HashMap
and Hashtable
----------------------------------------------------------------------------------------------------
HashMap HashTable
----------------------------------------------------------------------------------------------------
1. Predefined class in Java ,stores data in the form of
key-value pair 1. Class, stores data in the form of key value pair
Key
value
------------------
A Apple
B Ball
2.Allows one null key and
multiple null values 2.does
not null key and null values
if we insert null values --> NullpointerException
hm.put(null, null); HT: we cannot insert one null key and one null
value
hm.put("Raju",null)
ht.put(null,
"Apple"); --> ?
ht.put("Raju",null) --> ?
3.HashMap is non
synchronized. Hashtable is synchronized.
It is not-thread safe. fast It is thread-safe.slow
4.HashMap is traversed by
Iterator. Hashtable
is traversed by Enumerator and Iterator.
5. HashMap inherits AbstractMap
class. Hashtable
inherits Dictionary class.
HM
-- extends asbstractMap class HT -- extends Dictionary class
public class
Hashtable<K,V> extends
Dictionary<K,V>
implements
Map<K,V>, Cloneable, java.io.Serializable
Map -Interface in java -- only Abstract method - incomplete --
-
store the data in form of key, val pair
HashMap implements Map -- > implementation class
HashTable implements Map -->
implementation class
Synchronized vs.
Non-Synchronized
|
Aspect |
Synchronized |
Non-Synchronized |
|
Thread Access |
Allows only one thread to operate on an object at a time. |
Allows multiple threads to operate on an object
simultaneously. |
|
Performance |
Slower, as threads must wait for their turn to access the
object. |
Faster, as threads do not wait and can access the object
concurrently. |
|
Thread-Safety |
Thread-safe; prevents concurrent access issues. |
Not thread-safe; may lead to data inconsistencies when
accessed by multiple threads. |
|
Results |
Provides proper and consistent results due to controlled
access. |
May produce incorrect results due to concurrent access
without synchronization. |
Synchronised:
1. at a time , it allows only one thread to
operate on object
2. thread-1 tries to operate on obj, thread-2 ,3
will wait. so it increases waiting -- Performance wise - it is slow
3. thread -safe
4. it gives proper results
non synchronised :
1. at a time , it allows multiples threads to
operate on object
2. there is no waiting time for
Thread-1,2,3 -- Performance wise - it is
fast
3. it is not -thread -safe
4. it won't give proper results
Here’s a visual explanation of
synchronized versus non-synchronized access to resources in a multi-threaded
environment:
Synchronized Access:
+-------------------+ +-------------------+
| Thread 1 |
| Thread 2 |
| | | |
| Request access |
| Request access |
| to the object |
| to the object |
| | | |
| Access granted | | Waiting |
| (Object locked)| |
(Object locked) |
| Perform task |
| Waiting for |
| | |
Thread 1 to finish|
| Release access |
| Access granted |
| (Object unlocked)| |
Perform task |
|
|
|
|
- Thread 1 acquires access
to the object and performs its task while Thread 2 waits.
- Thread 2 can only access
the object after Thread
1 releases it.
- This
ensures thread safety but may reduce performance due to waiting times.
Non-Synchronized Access
+-------------------+ +-------------------+ +-------------------+
| Thread 1 |
| Thread 2 |
| Thread 3 |
| | | | | |
| Request access |
| Request access |
| Request access |
| to the object |
| to the object |
| to the object |
| | | | | |
| Access granted |
| Access granted |
| Access granted |
| Perform task |
| Perform task |
| Perform task |
| | | | | |
|
|
|
|
|
|
· Thread 1,
Thread 2, and Thread 3 all access the object simultaneously.
· There is no waiting or blocking, which
improves performance but can lead to inconsistent results if the object’s state
is modified by multiple threads concurrently.
get keys and
values from hashTable :
package CollectionFrameBasics;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Set;
public class
KeysSetFrromHashTable {
public
static void main(String[] args) {
//
Creating hashtable -Integer, String
Hashtable<Integer,
String> ht = new
Hashtable<Integer, String>();
//
Inserting key-value pairs into hash table
//
using put() method
ht.put(10,
"Apple");
ht.put(20,
"Ball");
ht.put(30,
"Cat");
System.out.println("ht
="+ ht);
//ht
=ht ={10=Apple, 20=Ball, 30=Cat}
// last class - keyset(), values()
for hashmap
//get
all keys from hashtable
// HW ht.keySet();
//get
all keys from hashtable using keys()
Enumeration<Integer> en = ht.keys();
while(en.hasMoreElements())
// it.hasNext() it.next() lit.hasPrevious() lit.previous()
{// true
//
check enumneration has any ele to iterate -- true
// no ele to iterate -- false
//
get val from en obj
// String key = en.nextElement();// error
Integer
iref = en.nextElement();
System.out.println("get
all key using enumeration=" + iref);
}
//HW
get all values from hashtable
}
}
Lambda
expression to get keys and values from hashmap:
·
Introduced in Java 8 version.
·
Lambda expression is used to get key and values from hashmap.
package CollectionFrameBasics;
import java.util.HashMap;
public class
LambdaExpressionToGetValsFromHahsMap {
public
static void main(String[] args) {
//Create
obj for HashMap class -
HashMap<String,
String > hm = new HashMap<String, String >();
// add some key, vals
hm.put("A",
"Apple");
hm.put("B",
"Ball");
hm.put("D",
"Dog");
hm.put("C",
"Cat");
//
Lambda expression
hm.forEach((k,v)->
{
System.out.println("Key
="+ k + ", value="+ v);
// System.out.println("keys="+
k);
// System.out.println("values="+
v);
}
);
}
}
// HW create hahstable and store some keys, values. get key and val
from hashtable using lambda expression
Amara 90898
Sita 98989
Raju 9789
// HW create hashtable and store
character, Integer values and get all
values ?
'A' 1
'B' 2
'C' 3
Note:
We don't have listItertaor() for
all collection classes
HW get values from "hash
set" using itertaor , listIteraor ()?
HW get values from "Linked hash set" using itertaor ,
listIterator ()?
HW get values from "Treeset" using itertaor , listIterator
()?
IP FAQ Count of each Character in string ?
i/p:
Rama
count of character i.e a - 2 times
m count
==1
R
- count =1 time
package CollectionFrameBasics;
import java.util.HashMap;
public class
CountOfEachCharFromStringUsingHAshMap {
public
static void main(String[] args) {
String
s = "rama";
// 0123
// r -1 a-2 times
// s.charAt(0);
// s.split("");
// to charArray --> tocharArray();
HashMap<Character,
Integer> hm = new HashMap<Character, Integer>();
for(int
i=0;i<=s.length()-1;i++)
{
char
ch = s.charAt(i);
// System.out.println("ch="+
ch);
if(hm.containsKey(ch))//
{} , {r=1}
{
// r, a
// if hashmap contais given char already, increase cnt by 1
hm.put(ch,
hm.get(ch) + 1);
}
else
{
// 1st time, setting the cnt =1
hm.put(ch,
1); //
// r,1 -> {r=1}
}
}
System.out.println("hm="+
hm);// hm={a=2, r=1, m=1}
//
get a count
System.out.println("get
a count ="+ hm.get('a') );// 2
}
}
FAQ Count of each word in string ?
i.p: "Rama is good. Sita is good"
hint : String [] sArr [] = s.split(" ");
Rama- 1
is - 2 times
good= 2 times
Sita = 1 time
package CollectionFrameBasics;
import java.util.HashMap;
public class CountOfEachWordFromStringUsingHashMap
{
public
static void main(String[] args) {
String
s = "Rama is good Sita is good";
// 0123
// Rama- 1
// is - 2 times
// good= 2 times
// Sita
= 1 time
//
egt each word from string
String
[] sarr = s.split(" ");
HashMap<String,
Integer> hm = new HashMap<String, Integer>();
for(String
word :sarr)
{
// System.out.println("word="+word);
if(hm.containsKey(word))//
{} ,
{
//
// if hashmap contais given char already, increase cnt by 1
hm.put(word,
hm.get(word) + 1);
}
else
{
// 1st time, setting the cnt =1
hm.put(word,
1); //
//
}
}
System.out.println("hm="+
hm);//hm={Sita=1, Rama=1, is=2, good=2}
//
get a count
System.out.println("get
a count ="+ hm.get('a') );// 2
}
}
FAQ Duplicate characters from String
package CollectionFrameBasics;
import java.util.HashMap;
public class
CountOfEachCharFromStringUsingHAshMap {
public
static void main(String[] args) {
String
s = "ramaa m";
// 0123
// r -1 a-2 times
// s.charAt(0);
// s.split("");
// to charArray --> tocharArray();
HashMap<Character,
Integer> hm = new HashMap<Character, Integer>();
for(int
i=0;i<=s.length()-1;i++)
{
char
ch = s.charAt(i);
// System.out.println("ch="+
ch);
if(hm.containsKey(ch))//
{} , {r=1}
{
// r, a
// if hashmap contais given char already, increase cnt by 1
hm.put(ch,
hm.get(ch) + 1);
}
else
{
// 1st time, setting the cnt =1
hm.put(ch,
1); //
// r,1 -> {r=1}
}
}
System.out.println("hm="+
hm);// hm={a=2, r=1, m=1}
//
get a count
System.out.println("get
a count ="+ hm.get('a') );// 2
////
hm={a=2, r=1, m=1}
//
display duplicate characters o/p:a
hm.forEach((k,v)->
{
//System.out.println("key
="+ k + ", val="+ v);
if(v>=2)
// if cnt >=2 , duplicate
{//
2 > =2 true
// 1 >=2
false
//
1>=2 false
System.out.println("duplicate
char ="+ k + ", cnt ="+ v);
// a
}
}
);
}
}
FAQ Unique Characters from String
package CollectionFrameBasics;
import java.util.HashMap;
public class
CountOfEachCharFromStringUsingHAshMap {
public
static void main(String[] args) {
String
s = "ramaa m";
// 0123
// r -1 a-2 times
// s.charAt(0);
// s.split("");
// to charArray --> tocharArray();
HashMap<Character,
Integer> hm = new HashMap<Character, Integer>();
for(int
i=0;i<=s.length()-1;i++)
{
char
ch = s.charAt(i);
// System.out.println("ch="+
ch);
if(hm.containsKey(ch))//
{} , {r=1}
{
// r, a
// if hashmap contais given char already, increase cnt by 1
hm.put(ch,
hm.get(ch) + 1);
}
else
{
// 1st time, setting the cnt =1
hm.put(ch,
1); //
// r,1 -> {r=1}
}
}
System.out.println("hm="+
hm);// hm={a=2, r=1, m=1}
//
get a count
System.out.println("get
a count ="+ hm.get('a') );// 2
////
hm={a=2, r=1, m=1}
//
display unique char - if cnt =1 - say
unique char
hm.forEach((k,v)->
{
//System.out.println("key
="+ k + ", val="+ v);
if(v==1)
// if cnt =1 - say unique char
{//
//
System.out.println("Unique
char ="+ k + ", cnt ="+ v);
// a
}
}
);
}
}
IP HW // FAQ Duplicate words from String "Ram is good sita is
good"?
O/p: is
good
IP HW // FAQ unique words from String "Ram is good sita is
good"?
o/p: Ram
Sita
Store Object
reference in Interface ref variable :
List - interface (Some Abstract Methods- Incomplete Methods)
-------------------------------------------------------------
| | | |
ArrayList(C) LinkedList Vector Stack
package CollectionFrameBasics;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
public class ArrayListBasics3 {
public
static void main(String[] args) {
//
Create array List of String
// ArrayList<String> al =
new ArrayList<String>();
//
store Array list obj ref into List interface variable
List<String>
al = new ArrayList<String>();
//
Interface ref variable = creating obj for Array List
// Right side we can write
Implementation classes only but not other classes
// List<String> al2 = new HashSet<String>();
//CE: Type mismatch: cannot convert from
HashSet<String> to List<String>
al.add("Ram");
al.add("sita");
al.add("Raju");
System.out.println("
List ="+ al);// =[Ram, sita, Raju]
//
Set (I) -Abstract method
//-----------------------------------------
//HashSet (c) LinkedHAshSet TreeSet
--> Implementation classes
//
create hashset obj and store String
values
// HashSet<String> hs =
new HashSet<String>();
Set<String> hs =
new HashSet<String>();
// // Interface =
implementation class object
//
// Set<String> hs =
new ArrayList<String>();
// // Type mismatch: cannot convert from
ArrayList<String> to Set<String>
//
Set<String> hs2 =
new LinkedHashSet<String>();
//
Set<String> hs3 =
new TreeSet<String>();
//
//
// // add
some values into hashset
hs.add("Ram");
hs.add("Sita");
hs.add("Raju");
System.out.println("
set="+ hs);
}
}
Store object reference to another object reference of Same class type:
package CollectionFrameBasics;
public class Demo
{
int
x = 10;
int
display()
{
System.out.println("x
= " + x);
return
0;
}
public
static void main(String[] args) {
//
create obj for Demo class
Demo
d1 = new Demo();
//
Store d1 ref variable into Demo class ref variable G1
Demo
G1 = d1;
//
point to same reference
//
G1 and D1 will point to the same object only
// 123961122
///
G1 =123961122
//
G1 and D1 will point to the same object only
//
check D1 and G1 address both are same
System.out.println("D1
obj addresss=" +d1.hashCode());
System.out.println("G1
obj addresss="+G1.hashCode());
//
create Demo class obj and ref variable M1
Demo
M1 = new Demo();
//
store M1 ref variable in Demo ref variable Q1
Demo
Q1 = M1;
//
Q1 And M1 will point to the same object only
//create
obj for Student class s1
Student
s1 = new Student();
//
Store s1 ref variable into demo ref variable Q2
// Demo Q2 = s1;
//
Type mismatch: cannot convert from Student to Demo
//
Note : Left side and Right side must be
of same class
//
updating the value of x using G1 = 25
//
reference variable
G1.x = 20;
System.out.println(G1.x);
// Point 1
System.out.println(d1.x);
// Point 2
}
}
o/p:
D1 obj addresss=123961122
G1 obj addresss=123961122
20
20
No comments:
Post a Comment