Introduction
In this lab, you will learn how to check if a Map in Java is empty. We will explore different methods for this common operation, starting with the straightforward isEmpty() method. You will also learn how to check the size of a map using the size() method and, importantly, how to handle cases where the map itself might be null to prevent potential NullPointerException errors. By the end of this lab, you will be proficient in determining the emptiness of Java Maps under various scenarios.
Use isEmpty() for Map Check
In this step, we will learn how to check if a Map in Java is empty using the isEmpty() method. A Map is a collection of key-value pairs, and checking if it's empty is a common operation.
First, let's create a new Java file named MapCheck.java in your ~/project directory. You can do this by right-clicking in the File Explorer on the left and selecting "New File", then typing MapCheck.java.
Now, open the MapCheck.java file in the editor and add the following code:
import java.util.HashMap;
import java.util.Map;
public class MapCheck {
public static void main(String[] args) {
// Create an empty Map
Map<String, Integer> emptyMap = new HashMap<>();
// Check if the map is empty using isEmpty()
boolean isEmpty = emptyMap.isEmpty();
// Print the result
System.out.println("Is the map empty? " + isEmpty);
// Create a non-empty Map
Map<String, Integer> nonEmptyMap = new HashMap<>();
nonEmptyMap.put("one", 1);
nonEmptyMap.put("two", 2);
// Check if the non-empty map is empty
boolean isNonEmpty = nonEmptyMap.isEmpty();
// Print the result
System.out.println("Is the non-empty map empty? " + isNonEmpty);
}
}
Let's break down the code:
import java.util.HashMap;andimport java.util.Map;: These lines import the necessary classes to work with Maps.Map<String, Integer> emptyMap = new HashMap<>();: This creates a new, emptyHashMap.HashMapis a common implementation of theMapinterface. We specify that the keys will beStringand the values will beInteger.boolean isEmpty = emptyMap.isEmpty();: This is where we use theisEmpty()method. It returnstrueif the map contains no key-value mappings, andfalseotherwise. The result is stored in a boolean variableisEmpty.System.out.println("Is the map empty? " + isEmpty);: This prints the result of the check to the console.- The code then repeats the process with a
nonEmptyMapto show howisEmpty()works when the map is not empty.
Save the MapCheck.java file (Ctrl+S or Cmd+S).
Now, open the Terminal at the bottom of the WebIDE. Make sure you are in the ~/project directory.
Compile the Java code using the javac command:
javac MapCheck.java
If there are no errors, a MapCheck.class file will be created in the ~/project directory.
Finally, run the compiled Java program using the java command:
java MapCheck
You should see the following output:
Is the map empty? true
Is the non-empty map empty? false
This output confirms that isEmpty() correctly identified the empty map and the non-empty map. Using isEmpty() is the recommended way to check if a map is empty, as it is clear and efficient.
Check Map Size with size()
In this step, we will learn how to get the number of key-value mappings in a Map using the size() method. This is useful when you need to know how many elements are currently stored in the map.
We will continue working with the MapCheck.java file we created in the previous step. Open MapCheck.java in the WebIDE editor.
Now, let's modify the main method to include checking the size of the maps. Replace the existing code in the main method with the following:
import java.util.HashMap;
import java.util.Map;
public class MapCheck {
public static void main(String[] args) {
// Create an empty Map
Map<String, Integer> emptyMap = new HashMap<>();
// Check the size of the empty map using size()
int emptySize = emptyMap.size();
// Print the result
System.out.println("Size of the empty map: " + emptySize);
// Create a non-empty Map
Map<String, Integer> nonEmptyMap = new HashMap<>();
nonEmptyMap.put("one", 1);
nonEmptyMap.put("two", 2);
nonEmptyMap.put("three", 3); // Add one more element
// Check the size of the non-empty map
int nonEmptySize = nonEmptyMap.size();
// Print the result
System.out.println("Size of the non-empty map: " + nonEmptySize);
}
}
Let's look at the changes:
int emptySize = emptyMap.size();: This line calls thesize()method on theemptyMap. Thesize()method returns the number of key-value pairs in the map as an integer. The result is stored in an integer variableemptySize.System.out.println("Size of the empty map: " + emptySize);: This prints the size of the empty map.- We also added an extra element (
"three", 3) to thenonEmptyMapto show how the size changes. int nonEmptySize = nonEmptyMap.size();: This callssize()on thenonEmptyMapto get its size.System.out.println("Size of the non-empty map: " + nonEmptySize);: This prints the size of the non-empty map.
Save the MapCheck.java file (Ctrl+S or Cmd+S).
Now, open the Terminal and make sure you are in the ~/project directory.
Compile the modified Java code:
javac MapCheck.java
If the compilation is successful, run the program:
java MapCheck
You should see the following output:
Size of the empty map: 0
Size of the non-empty map: 3
This output shows that size() correctly reported the number of elements in both the empty and non-empty maps. The size() method is a simple and effective way to determine the current number of entries in a Java Map.
Handle Null Maps
In the previous steps, we worked with maps that were either empty or contained elements. However, it's important to consider what happens if a Map variable is null. A null reference means the variable doesn't point to any object in memory. Trying to call a method like isEmpty() or size() on a null map will result in a NullPointerException, which is a common error in Java.
In this step, we will learn how to safely handle potential null map references before attempting to check their emptiness or size.
Open the MapCheck.java file in the WebIDE editor again.
Let's add code to demonstrate and handle a null map. Modify the main method to include the following:
import java.util.HashMap;
import java.util.Map;
public class MapCheck {
public static void main(String[] args) {
// Create an empty Map
Map<String, Integer> emptyMap = new HashMap<>();
// Check the size of the empty map using size()
int emptySize = emptyMap.size();
// Print the result
System.out.println("Size of the empty map: " + emptySize);
// Create a non-empty Map
Map<String, Integer> nonEmptyMap = new HashMap<>();
nonEmptyMap.put("one", 1);
nonEmptyMap.put("two", 2);
nonEmptyMap.put("three", 3); // Add one more element
// Check the size of the non-empty map
int nonEmptySize = nonEmptyMap.size();
// Print the result
System.out.println("Size of the non-empty map: " + nonEmptySize);
// Declare a Map variable but don't initialize it (it will be null)
Map<String, Integer> nullMap = null;
// --- Handling the null map ---
// Check if the map is null before calling methods
if (nullMap == null) {
System.out.println("The nullMap is null.");
} else {
// This block will not be executed for nullMap
System.out.println("Is the nullMap empty? " + nullMap.isEmpty());
System.out.println("Size of the nullMap: " + nullMap.size());
}
// A safer way to check if a map is empty (handles null)
boolean isNullMapEmpty = (nullMap == null || nullMap.isEmpty());
System.out.println("Is the nullMap considered empty (including null)? " + isNullMapEmpty);
// A safer way to get the size (handles null)
int nullMapSize = (nullMap == null) ? 0 : nullMap.size();
System.out.println("Size of the nullMap (handling null): " + nullMapSize);
}
}
Here's what we added:
Map<String, Integer> nullMap = null;: This declares aMapvariable but explicitly sets it tonull.if (nullMap == null) { ... }: This is the crucial part for handlingnull. We check if thenullMapvariable isnullbefore trying to call any methods on it. If it isnull, we print a message. If it were notnull, theelseblock would execute, and we could safely callisEmpty()andsize().boolean isNullMapEmpty = (nullMap == null || nullMap.isEmpty());: This is a common pattern to check if a map is effectively "empty", which includes the case where the map reference itself isnull. The||(OR) operator means ifnullMap == nullis true, the whole expression is true, andnullMap.isEmpty()is not even evaluated, preventing theNullPointerException.int nullMapSize = (nullMap == null) ? 0 : nullMap.size();: This uses the ternary operator (? :) to safely get the size. IfnullMapisnull, the expression evaluates to0. Otherwise, it evaluates tonullMap.size().
Save the MapCheck.java file (Ctrl+S or Cmd+S).
Compile the modified code in the Terminal:
javac MapCheck.java
Run the program:
java MapCheck
You should see output similar to this:
Size of the empty map: 0
Size of the non-empty map: 3
The nullMap is null.
Is the nullMap considered empty (including null)? true
Size of the nullMap (handling null): 0
Notice that the lines inside the else block for nullMap were not executed, and we successfully checked if the nullMap was null and got its size (treating null as size 0) without causing an error.
Handling null references is very important in Java to prevent NullPointerExceptions and make your programs more robust. Always consider if a variable could be null before calling methods on it.
Summary
In this lab, we learned how to check if a Map in Java is empty. We explored the primary method for this, isEmpty(), which directly indicates whether a map contains any key-value pairs. We saw how to apply this method to both newly created empty maps and maps that have been populated with data, demonstrating its straightforward usage and the boolean result it returns.
Beyond the basic isEmpty() check, we also covered alternative methods like using size() to determine if a map's size is zero, which is functionally equivalent to checking for emptiness. Furthermore, we addressed the crucial aspect of handling potential null map references to prevent NullPointerExceptions, emphasizing the importance of null checks before attempting to call methods on a map object.



