1. Introduction

The Properties class in Java, a part of the java.util package, is used to maintain a set of properties, which can be loaded from or saved to a stream. On the other hand, a Map is a collection of key-value pairs. There might be situations where we want to convert a Properties object to a Map for easier and more versatile operations on the data.

2. Program Steps

1. Import the necessary libraries.

2. Create and initialize a Properties object.

3. Convert the Properties object to a Map.

4. Display the contents of the Map.

3. Code Program

// Step 1: Import the necessary libraries
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

public class PropertiesToMapExample {

    public static void main(String[] args) {

        // Step 2: Create and initialize a Properties object
        Properties properties = new Properties();
        properties.setProperty("username", "admin");
        properties.setProperty("password", "admin123");

        // Step 3: Convert the Properties object to a Map
        Map<String, String> map = new HashMap<>();
        Set<String> propertyNames = properties.stringPropertyNames();
        for (String key : propertyNames) {
            map.put(key, properties.getProperty(key));
        }

        // Step 4: Display the contents of the Map
        System.out.println("Map Object:");
        map.forEach((key, value) -> System.out.println(key + "=" + value));
    }
}

Output:

Map Object:
password=admin123
username=admin

4. Step By Step Explanation

Step 1: Import the HashMap, Map, Properties, and Set classes from the java.util package.

Step 2: A Properties object is created and initialized with a username and password.

Step 3: The Properties object is converted to a Map. The stringPropertyNames method is used to get the set of keys (property names), and then each key-value pair is put into the Map.

Step 4: The contents of the Map are displayed, showing the converted key-value pairs from the Properties object.