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

Java Map Collection

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.

  • Import necessary classes:

First, import the necessary classes from the java.util package.

import java.util.HashMap;
import java.util.Map;
  • Create a 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<>();
  • Add elements to the Map:

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);
  • Retrieve values from the Map:

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
  • Remove elements from the Map:

Use the remove() method to remove a key-value pair from the map based on the key.

ages.remove("Alice");
  • Check if a key is in the Map:

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
  • Iterate over the Map:

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());
}
  • Find the size of the Map:

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
  • Clear the Map:

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.

  1. Creating and initializing HashMap in Java:

    • HashMap is a widely used implementation of the Map interface in Java.
    Map<String, Integer> hashMap = new HashMap<>();
    
  2. Working with keys and values in Java Map:

    • You can add, retrieve, and remove elements using keys and values.
    hashMap.put("One", 1);
    int value = hashMap.get("One"); // Retrieves the value associated with key "One"
    
  3. Common operations on Java Map collection:

    • Various operations include 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
    
  4. Iterating through keys and values in a Map in Java:

    • You can iterate through keys, values, or key-value pairs.
    for (String key : hashMap.keySet()) {
        System.out.println("Key: " + key + ", Value: " + hashMap.get(key));
    }
    
  5. Different types of Map implementations in Java:

    • Besides 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<>();
    
  6. ConcurrentHashMap and thread safety in Java Map:

    • ConcurrentHashMap provides thread safety for concurrent access.
    Map<String, Integer> concurrentMap = new ConcurrentHashMap<>();
    
  7. Sorting and ordering entries in Java Map:

    • For sorting, you can use a 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));
    
  8. Merging and combining maps in Java:

    • Use 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