package
org.learn.collection.map.hmap;
import
java.util.AbstractMap;
import
java.util.HashMap;
import
java.util.Map;
public
class
DemoPutIfAbsentHashMap {
public
static
void
main(String[] args) {
Map<String, String> mapSportsPersonality =
new
HashMap<>();
mapSportsPersonality.put(
"Tennis"
,
"Federer"
);
mapSportsPersonality.put(
"baseball"
,
"Trout"
);
mapSportsPersonality.put(
"Basketball"
,
"Jordan"
);
mapSportsPersonality.put(
"Golf"
,
"Woods"
);
System.out.println(
"Demo of putIfAbsent method: "
);
demoPutIfAbsent(mapSportsPersonality);
}
private
static
void
demoPutIfAbsent(Map<String, String> mapSportsPersonality) {
System.out.println(
"1. Orignal HashMap:"
+ mapSportsPersonality);
Map.Entry<String, String> newEntry =
new
AbstractMap.SimpleEntry<String, String>(
"Tennis"
,
"Djokovic"
);
System.out.println(
"2. New entry to add:\n"
+ newEntry);
String existingValue = mapSportsPersonality.putIfAbsent(newEntry.getKey(), newEntry.getValue());
if
(
null
!= existingValue) {
System.out.println(
"Key :"
+ newEntry.getKey() +
" already exists, Record not inserted"
);
System.out.println(
"Entries in hashmap:"
+ mapSportsPersonality);
}
else
{
System.out.println(
"New record added to hashMap:\n"
+mapSportsPersonality);
}
newEntry =
new
AbstractMap.SimpleEntry<String, String>(
"Boxer"
,
"Ali"
);
System.out.println(
"3. New entry to add:\n"
+ newEntry);
existingValue = mapSportsPersonality.putIfAbsent(newEntry.getKey(), newEntry.getValue());
if
(
null
!= existingValue) {
System.out.println(
"Key :"
+ newEntry.getKey() +
" already exists, Record not inserted"
);
System.out.println(
"Entries in hashmap:"
+ mapSportsPersonality);
}
else
{
System.out.println(
"New record added to hashMap:\n"
+ mapSportsPersonality);
}
}
}