How to create a Map with Initial Key-Value Pairs in Java - Step by Step Examples



How to create a Map with Initial Key-Value Pairs in Java ?

Answer

To create a map with initial key-value pairs in Java, you can use the HashMap constructor along with the put method or use the Map.of method. These create a new map object with predefined key-value pairs.



✐ Examples

1 Creating a Map with Initial Key-Value Pairs Using HashMap and put Method

We can create a map in Java with initial key-value pairs using the HashMap constructor and the put method to add entries.

For example,

  1. We start by importing the java.util.HashMap package, which provides the HashMap class needed to create a map.
  2. We then declare a variable named myMap of type HashMap. This variable will hold our map with initial key-value pairs.
  3. We use the new HashMap<>() constructor to create a new, empty HashMap object. In Java, the HashMap constructor initializes the map with no key-value pairs.
  4. We use the put method to add key-value pairs to the map. In this example, the map has integer keys and string values.
  5. We can now perform various operations on this map, such as adding more key-value pairs, checking for the presence of keys, and retrieving values.

Java Program

import java.util.HashMap;

public class Main {
    public static void main(String[] args) {
        // Declare a map with initial key-value pairs
        HashMap<Integer, String> myMap = new HashMap<>();
        myMap.put(1, "one");
        myMap.put(2, "two");
        myMap.put(3, "three");

        // Operations on the map
        for (HashMap.Entry<Integer, String> entry : myMap.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
    }
}

Output

1: one
2: two
3: three

2 Creating a Map with Initial Key-Value Pairs Using Map.of Method

We can create a map in Java with initial key-value pairs using the Map.of method, which initializes a map with predefined key-value pairs.

For example,

  1. We start by importing the java.util.Map package, which provides the Map interface and related methods.
  2. We then declare a variable named studentGrades of type Map. This variable will hold our map with initial key-value pairs where keys are strings (student names) and values are characters (grades).
  3. We use the Map.of method to create a new map object with initial key-value pairs. In Java, the Map.of method allows us to specify key-value pairs directly as arguments.
  4. The newly created map is now assigned to the studentGrades variable. In this example, the map has string keys and string values representing grades.
  5. We can now perform various operations on this map, such as adding more key-value pairs (Note: the map created by Map.of is immutable), checking for the presence of keys, and retrieving values.

Java Program

import java.util.Map;

public class Main {
    public static void main(String[] args) {
        // Declare a map with initial key-value pairs
        Map<String, String> studentGrades = Map.of(
            "Alice", "A",
            "Bob", "B",
            "Charlie", "C"
        );

        // Operations on the map
        for (Map.Entry<String, String> entry : studentGrades.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
    }
}

Output

Alice: A
Bob: B
Charlie: C

3 Creating a Map with Integer Keys and Float Values

We can create a map in Java with initial key-value pairs where keys are integers and values are floats using the HashMap constructor and the put method.

For example,

  1. We start by importing the java.util.HashMap package, which provides the HashMap class needed to create a map.
  2. We then declare a variable named productPrices of type HashMap. This variable will hold our map with initial key-value pairs where keys are integers (product IDs) and values are floats (prices).
  3. We use the new HashMap<>() constructor to create a new, empty HashMap object. In Java, the HashMap constructor initializes the map with no key-value pairs.
  4. We use the put method to add key-value pairs to the map. In this example, the map has integer keys and float values.
  5. We can now perform various operations on this map, such as adding more key-value pairs, checking for the presence of keys, and retrieving values.

Java Program

import java.util.HashMap;

public class Main {
    public static void main(String[] args) {
        // Declare a map with initial key-value pairs
        HashMap<Integer, Float> productPrices = new HashMap<>();
        productPrices.put(101, 29.99f);
        productPrices.put(102, 39.99f);
        productPrices.put(103, 49.99f);

        // Operations on the map
        for (HashMap.Entry<Integer, Float> entry : productPrices.entrySet()) {
            System.out.println("Product " + entry.getKey() + ": $" + entry.getValue());
        }
    }
}

Output

Product 101: $29.99
Product 102: $39.99
Product 103: $49.99

Summary

In this tutorial, we learned How to create a Map with Initial Key-Value Pairs in Java language with well detailed examples.




More Java Maps Tutorials

  1. How to create an Empty Map in Java ?
  2. How to create a Map with Initial Key-Value Pairs in Java ?
  3. How to Print a Map in Java ?
  4. How to Add a Key-Value Pair to a Map in Java ?
  5. How to Set a Default Value for a Key in a Map in Java ?
  6. How to Update the Value for a Key in a Map in Java ?
  7. How to Check if a Map is Empty in Java ?
  8. How to Check if a Key Exists in a Map in Java ?
  9. How to Check if a Value Exists in a Map in Java ?
  10. How to Get the Value Associated with a Key in a Map in Java ?
  11. How to Remove a Key-Value Pair from a Map in Java ?
  12. How to Remove Key-Value Pairs from a Map Based on Values in Java ?
  13. How to Clear All Key-Value Pairs from a Map in Java ?
  14. How to Iterate Over Keys in a Map in Java ?
  15. How to Iterate Over Values in a Map in Java ?
  16. How to Iterate Over Entries (Key-Value Pairs) in a Map in Java ?
  17. How to Get the Size (Number of Key-Value Pairs) of a Map in Java ?
  18. How to Convert a Map to an Array of Keys in Java ?
  19. How to Convert a Map to an Array of Values in Java ?
  20. How to Merge Two Maps in Java ?
  21. How to Copy a Map in Java ?
  22. How to Check if Two Maps are Equal in Java ?
  23. How to Sort a Map by Keys in Java ?
  24. How to Sort a Map by Values in Java ?
  25. How to Filter a Map Based on Keys in Java ?
  26. How to Filter a Map Based on Values in Java ?
  27. How to Reduce Values in a Map to a Single Value in Java ?
  28. How to Convert an Array of Key-Value Pairs to a Map in Java ?
  29. How to Convert a Map to a JSON String in Java ?
  30. How to Convert a JSON String to a Map in Java ?
  31. How to Swap Keys and Values in a Map in Java ?
  32. How to Create a Map of Maps in Java ?
  33. How to Iterate Over a Map of Maps in Java ?