Site icon

putIfAbsent method of HashMap in java (with example)

Prototype of putIfAbsent method

Program – putIfAbsent method of HashMap in java

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);
		}
	}
}

Output – putIfAbsent method of HashMap in java

Demo of putIfAbsent method: 
1. Orignal HashMap:{Tennis=Federer, Golf=Woods, baseball=Trout, Basketball=Jordan}
2. New entry to add:
Tennis=Djokovic
Key :Tennis already exists, Record not inserted
Entries in hashmap:{Tennis=Federer, Golf=Woods, baseball=Trout, Basketball=Jordan}
3. New entry to add:
Boxer=Ali
New record added to hashMap:
{Tennis=Federer, Golf=Woods, baseball=Trout, Basketball=Jordan, Boxer=Ali}

Oracle reference

Exit mobile version