Maps
The Map
interface provides a way to map keys to values. This tutorial will teach you how to use maps in Java.
Creating a Map
To create a map, use the HashMap
class:
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Map<String, Integer> ages = new HashMap<>();
ages.put("Alice", 25);
ages.put("Bob", 30);
ages.put("Charlie", 35);
System.out.println(ages);
}
}
Accessing Values in a Map
You can access values in a map using the get
method:
public class Main {
public static void main(String[] args) {
Map<String, Integer> ages = new HashMap<>();
ages.put("Alice", 25);
ages.put("Bob", 30);
ages.put("Charlie", 35);
System.out.println(ages.get("Bob")); // Outputs: 30
}
}
Removing Entries from a Map
Use the remove
method to remove entries from a map:
public class Main {
public static void main(String[] args) {
Map<String, Integer> ages = new HashMap<>();
ages.put("Alice", 25);
ages.put("Bob", 30);
ages.put("Charlie", 35);
ages.remove("Bob");
System.out.println(ages); // Outputs: {Alice=25, Charlie=35}
}
}
Iterating Over a Map
You can iterate over a map using a for-each loop:
public class Main {
public static void main(String[] args) {
Map<String, Integer> ages = new HashMap<>();
ages.put("Alice", 25);
ages.put("Bob", 30);
ages.put("Charlie", 35);
for (Map.Entry<String, Integer> entry : ages.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
Continue exploring our intermediate tutorials to learn more about Java programming.