Java Tutorial
Operators
Flow Control
String
Number and Date
Built-in Classes
Array
Class and Object
Inheritance and Polymorphism
Exception Handling
Collections, Generics and Enumerations
Reflection
Input/Output Stream
Annotation
A Map
in Java is an interface that represents a data structure that allows you to store key-value pairs. Java provides several concrete implementations of the Map
interface, such as HashMap
, TreeMap
, and LinkedHashMap
. This tutorial will introduce you to the basic concepts and operations of Java Maps.
First, import the necessary classes from the java.util
package.
import java.util.HashMap; import java.util.Map;
You can create a Map
by specifying the key and value types within angle brackets (< >
). In this example, we will create a Map
to store the ages of people using their names as keys.
Map<String, Integer> ages = new HashMap<>();
You can use the put()
method to add key-value pairs to the map.
ages.put("Alice", 30); ages.put("Bob", 25); ages.put("Charlie", 22);
Use the get()
method to retrieve the value associated with a key. If the key is not found in the map, get()
returns null
.
int ageOfAlice = ages.get("Alice"); System.out.println("Age of Alice: " + ageOfAlice); // Output: Age of Alice: 30 int ageOfUnknown = ages.getOrDefault("Unknown", -1); System.out.println("Age of Unknown: " + ageOfUnknown); // Output: Age of Unknown: -1
Use the remove()
method to remove a key-value pair from the map based on the key.
ages.remove("Alice");
You can use the containsKey()
method to check if a key is present in the map.
boolean hasAlice = ages.containsKey("Alice"); System.out.println("Has Alice: " + hasAlice); // Output: Has Alice: false
You can iterate over the keys, values, or entries (key-value pairs) of the map using the keySet()
, values()
, or entrySet()
methods, respectively.
// Iterate over keys for (String name : ages.keySet()) { System.out.println(name); } // Iterate over values for (Integer age : ages.values()) { System.out.println(age); } // Iterate over entries for (Map.Entry<String, Integer> entry : ages.entrySet()) { System.out.println(entry.getKey() + ": " + entry.getValue()); }
Use the size()
method to get the number of key-value pairs in the map.
int size = ages.size(); System.out.println("Size: " + size); // Output: Size: 2
Use the clear()
method to remove all key-value pairs from the map.
ages.clear();
This tutorial covered the basic concepts and operations of Java Maps, including creating, adding, retrieving, removing, and iterating over elements. Maps are a powerful and versatile data structure that can be used to store and manipulate key-value pairs efficiently.
Creating and initializing HashMap in Java:
HashMap
is a widely used implementation of the Map
interface in Java.Map<String, Integer> hashMap = new HashMap<>();
Working with keys and values in Java Map:
hashMap.put("One", 1); int value = hashMap.get("One"); // Retrieves the value associated with key "One"
Common operations on Java Map collection:
put
, get
, remove
, containsKey
, containsValue
, and size
.hashMap.put("Two", 2); boolean containsKey = hashMap.containsKey("Two"); // Returns true int size = hashMap.size(); // Returns the size of the map
Iterating through keys and values in a Map in Java:
for (String key : hashMap.keySet()) { System.out.println("Key: " + key + ", Value: " + hashMap.get(key)); }
Different types of Map implementations in Java:
HashMap
, other common implementations include TreeMap
(sorted), LinkedHashMap
(maintains insertion order), and HashTable
(thread-safe, legacy).Map<String, Integer> treeMap = new TreeMap<>(); Map<String, Integer> linkedHashMap = new LinkedHashMap<>(); Map<String, Integer> hashTable = new Hashtable<>();
ConcurrentHashMap and thread safety in Java Map:
ConcurrentHashMap
provides thread safety for concurrent access.Map<String, Integer> concurrentMap = new ConcurrentHashMap<>();
Sorting and ordering entries in Java Map:
TreeMap
. Alternatively, you can convert entries to a list and sort it.Map<String, Integer> treeMap = new TreeMap<>(); // or List<Map.Entry<String, Integer>> entryList = new ArrayList<>(hashMap.entrySet()); Collections.sort(entryList, Comparator.comparing(Map.Entry::getKey));
Merging and combining maps in Java:
putAll
to merge one map into another.Map<String, Integer> map1 = new HashMap<>(); map1.put("A", 1); Map<String, Integer> map2 = new HashMap<>(); map2.put("B", 2); map1.putAll(map2); // Merges map2 into map1