YouTip LogoYouTip

Java Hashmap Remove

# Java HashMap remove() Method [![Image 3: Java HashMap](#) Java HashMap](#) The remove() method is used to delete the key-value pair corresponding to a specified key in a HashMap. The syntax for the remove() method is: hashmap.remove(Object key, Object value); **Note:** hashmap is an object of the HashMap class. **Parameter Description:** * key - The key * value (optional) - The value corresponding to the key in the key-value pair ### Return Value If only the key is specified, it returns the value associated with the specified key. If the specified key maps to null or the key does not exist in the HashMap, this method returns null. If both key and value are specified, it returns true if the deletion is successful, otherwise it returns false. ### Example The following example demonstrates the use of the remove() method: ## Example import java.util.HashMap; class Main { public static void main(String[] args){ HashMap sites =new HashMap(); sites.put(1, "Google"); sites.put(2, ""); sites.put(3, "Taobao"); System.out.println("HashMap: "+ sites); // Delete the mapping with key 2 String siteName = sites.remove(2);// return System.out.println("Return value: "+ siteName); System.out.println("HashMap after deletion: "+ sites); } } The output of the above program is: HashMap: {1=Google, 2=, 3=Taobao}Return value: TutorialHashMap after deletion: {1=Google, 3=Taobao} In the above example, we created a HashMap named sites. The code later uses the remove() method to delete the value corresponding to a specified key in sites, and the return value is that value. The remove() method takes two parameters: key and value: ## Example import java.util.HashMap; class Main { public static void main(String[] args){ HashMap sites =new HashMap(); sites.put(1, "Google"); sites.put(2, ""); sites.put(3, "Taobao"); System.out.println("HashMap: "+ sites); // Delete the mapping with key 2 Boolean flag1 = sites.remove(1, "Google");// return true Boolean flag2 = sites.remove(2, "Weibo");// return false System.out.println("Return value flag1: "+ flag1); System.out.println("Return value flag2: "+ flag2); System.out.println("HashMap after deletion: "+ sites); } } The output of the above program is: Return value flag1: trueReturn value flag2: falseHashMap after deletion: {2=, 3=Taobao} In the above example, we created a HashMap named sites containing 3 elements. Note these two lines: Boolean flag1 = sites.remove(1, "Google"); // Returns true for an existing key-value pairBoolean flag2 = sites.remove(2, "Weibo"); // Returns false for a non-existent key-value pair The remove() method includes both key and value. If the HashMap contains this key-value pair, it returns true; otherwise, it returns false. [![Image 4: Java HashMap](#) Java HashMap](#)
← Java Hashmap IsemptyPython3 File Tell β†’