HashMap Methods
Part of the Logic & Flow section of Coddy's Java journey — lesson 16 of 59.
HashMap provides many useful methods for common operations. Here are a few important ones:
isEmpty(): Checks if theHashMapis empty. Returnstrueif it contains no key-value mappings,falseotherwise.
size(): Returns the number of key-value mappings in theHashMap.
clear(): Removes all of the mappings from theHashMap. The map will be empty after this call returns.
For example let first create a HashMap:
HashMap<String, Integer> scores = new HashMap<>();To check if the HashMap is empty:
System.out.println(scores.isEmpty());
// Output: trueIf we'll add an item:
scores.put("Coddy", 100);
System.out.println(scores.isEmpty());
// Output: falseThe size() method returns the number of key-value pairs in the HashMap.
System.out.println(scores.size());
// Output: 1The clear() method removes all key-value mappings from the HashMap.
scores.clear();
System.out.println(scores.isEmpty());
// Output: trueChallenge
EasyCreate a method named <strong>testHashMapMethods</strong> that takes a HashMap named <strong>data</strong> as input. The method should perform the following operations:
Check if the HashMap is empty and print:
Is empty: trueorIs empty: falseGet the number of key-value mappings and print:
Size: X(where<i>X</i>is the size of the HashMap).- Remove all mappings from the HashMap using
<strong>clear()</strong>. Check if the HashMap is empty again after clearing and print:
Is empty after clear: true
Cheat sheet
Common HashMap utility methods:
isEmpty(): Returnstrueif the HashMap contains no key-value mappingssize(): Returns the number of key-value mappings in the HashMapclear(): Removes all mappings from the HashMap
HashMap<String, Integer> scores = new HashMap<>();
// Check if empty
System.out.println(scores.isEmpty()); // true
// Add item and check again
scores.put("Coddy", 100);
System.out.println(scores.isEmpty()); // false
// Get size
System.out.println(scores.size()); // 1
// Clear all mappings
scores.clear();
System.out.println(scores.isEmpty()); // trueTry it yourself
// --- Modules to convert string of hashmap to hashmap ---
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
// -----------------------------
import java.util.HashMap;
import java.util.Scanner;
public class Main {
public static void testHashMapMethods(HashMap<String, Integer> data) {
// Write your code here
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String hashMapString = scanner.nextLine();
// Convert String of HashMap to HashMap
Type mapType = new TypeToken<HashMap<String, Integer>>(){}.getType();
HashMap<String, Integer> data = new Gson().fromJson(hashMapString, mapType);
testHashMapMethods(data);
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysMatrix Addition & SubstractionJagged Arrays3D Arrays And BeyondCommon 2D Array PatternsRecap - All About Arrays2HashMap Part 1
What is a HashMap?Declare a HashMapAccessing ValuesCheck If Key ExistsModifying DictionariesRecap - HashMap3HashMap Part 2
HashMap MethodsIterate with keySet()Iterate with entrySet()Nested HashMapRecap - Manage WarehouseRecap - HashMap Operations6Advanced Control Flow
Label StatementsSwitch ExpressionPattern MatchingGuard ClausesRecap - Control Flow