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;
and import java.util.Map;
: These lines import the necessary classes to work with Maps.
Map<String, Integer> emptyMap = new HashMap<>();
: This creates a new, empty HashMap
. HashMap
is a common implementation of the Map
interface. We specify that the keys will be String
and the values will be Integer
.
boolean isEmpty = emptyMap.isEmpty();
: This is where we use the isEmpty()
method. It returns true
if the map contains no key-value mappings, and false
otherwise. The result is stored in a boolean variable isEmpty
.
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
nonEmptyMap
to show how isEmpty()
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.