Convert Properties to Map in Java

1. Introduction

Properties in Java are often used to manage application settings and configurations through key-value pairs stored in a simple, file-based format. However, there might be scenarios where you need to manipulate these configurations as a Map for enhanced functionality, such as leveraging Java Stream API operations or integrating with APIs that require maps. This blog post will demonstrate how to convert Properties to a Map, facilitating operations that are more complex or not directly supported by the Properties class.

2. Program Steps

1. Create and populate a Properties object.

2. Convert the Properties object to a Map<String, String>.

3. Display the resulting Map.

3. Code Program

import java.util.*;
import java.util.stream.Collectors;

public class PropertiesToMap {
    public static void main(String[] args) {
        // Step 1: Creating and populating a Properties object
        Properties properties = new Properties();
        properties.setProperty("database.url", "jdbc:mysql://localhost:3306/myDb");
        properties.setProperty("database.user", "user1");
        properties.setProperty("database.password", "pass123");

        // Step 2: Converting Properties to Map<String, String>
        Map<String, String> map = properties.entrySet().stream()
                .collect(Collectors.toMap(
                        e -> e.getKey().toString(),
                        e -> e.getValue().toString()));

        // Step 3: Displaying the resulting Map
        System.out.println("Map from Properties: " + map);
    }
}

Output:

Map from Properties: {database.password=pass123, database.url=jdbc:mysql://localhost:3306/myDb, database.user=user1}

Explanation:

1. The program starts by creating a Properties object and populating it with key-value pairs that represent hypothetical database configuration settings. The Properties class, which extends Hashtable<Object,Object>, allows for the storage of strings in a key-value format.

2. To convert the Properties object into a Map<String, String>, the program utilizes the Java Stream API. The properties.entrySet().stream() call creates a stream of Map.Entry objects. Each entry's key and value are converted to strings using the toString method. The stream is then collected into a new Map<String, String> using Collectors.toMap(), which requires functions to extract the key and value for each map entry.

3. Finally, the resulting Map is printed to the console. This Map contains all the key-value pairs from the original Properties object, now accessible in a format that supports a broader range of operations and manipulations provided by the Map interface.

4. This example demonstrates a practical use case for converting Properties to a Map<String, String> in Java, leveraging the Stream API for efficient transformation and facilitating enhanced data processing capabilities.

Comments