Convert Map to Properties in Java

1. Introduction

In this blog post, we will see how to convert a HashMap to Properties in Java.

2. Program Steps

1. Create a Map<String, String> and populate it with key-value pairs.

2. Create an instance of Properties.

3. Iterate over the Map's entry set and store each entry in the Properties object.

4. Display the Properties object.

3. Code Program

import java.util.*;
import java.util.Map.Entry;

public class MapToProperties {
    public static void main(String[] args) {
        // Step 1: Creating and populating a Map
        Map<String, String> map = new HashMap<>();
        map.put("database.url", "jdbc:mysql://localhost:3306/myDb");
        map.put("database.user", "user1");
        map.put("database.password", "pass123");

        // Step 2: Creating an instance of Properties
        Properties properties = new Properties();

        // Step 3: Iterating over the Map and storing entries in Properties
        for (Entry<String, String> entry : map.entrySet()) {
            properties.setProperty(entry.getKey(), entry.getValue());
        }

        // Step 4: Displaying the Properties object
        properties.list(System.out);
    }
}

Output:

-- listing properties --
database.password=pass123
database.url=jdbc:mysql://localhost:3306/myDb
database.user=user1

Explanation:

1. The program begins by creating a HashMap<String, String> named map and populating it with key-value pairs that could represent, for example, database configuration settings.

2. A Properties object is then created. Unlike a generic Map, a Properties object is specifically designed to hold strings as both keys and values, and it provides methods tailored for handling property data, such as load, store, and setProperty.

3. The program iterates over the map's entry set using a for-each loop. Within this loop, each key-value pair from the map is added to the properties object using the setProperty method. This method takes two String parameters: the key and the value.

4. Finally, the properties object is printed to the console using the list method, which outputs the list of key-value pairs contained in the properties object.

5. This example demonstrates how to convert a Map<String, String> to a Properties object, a common task when dealing with configurations in Java applications.

Comments