How to Convert Properties to Map in Java

Convert Properties to Map in Java

This example program about, How to convert properties to map in java. The example was tested with environment and shared in the post.

1) Converting Properties to Map in Java

public static Map<Object, Object> convertToMap(final String filePath) {

	// creating the properties object
	Properties properties = new Properties();

	// declaring the map object
	Map<Object, Object> propertyMap  = null;
	
	// creating file object
	File file = new File(filePath);

	FileReader fr = null;
	
	try {
		
		fr = new FileReader(file);

		properties.load(fr);
		
		propertyMap = new HashMap<Object, Object>(properties);

	} catch (FileNotFoundException e) {
		
		System.out.println(e.getMessage());
		e.printStackTrace();
		
	} catch (IOException e) {

		System.out.println(e.getMessage());
		e.printStackTrace();
	}
	
	return propertyMap;
}

2) Complete Example

package com.dineshkrish.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

public class PropertiesToMap {
	
	public static Map<Object, Object> convertToMap(final String filePath) {
	
		// creating the properties object
		Properties properties = new Properties();

		// declaring the map object
		Map<Object, Object> propertyMap  = null;
		
		// creating file object
		File file = new File(filePath);

		FileReader fr = null;
		
		try {
			
			fr = new FileReader(file);

			properties.load(fr);
			
			propertyMap = new HashMap<Object, Object>(properties);

		} catch (FileNotFoundException e) {
			
			System.out.println(e.getMessage());
			e.printStackTrace();
			
		} catch (IOException e) {

			System.out.println(e.getMessage());
			e.printStackTrace();
		}
		
		return propertyMap;
	}

	public static void main(String[] args) {

		String filePath = "my.properties";
		
		// Converting properties to map object
		Map<Object, Object> propertyMap = convertToMap(filePath);
		
		if(propertyMap != null) {
			
			Set<Object> keys = propertyMap.keySet();
			
			Iterator<Object> iterator = keys.iterator();
			
 			while(iterator.hasNext()) {
 				
 				String key = String.valueOf(iterator.next());
 				String value = String.valueOf(propertyMap.get(key));
 				
 				System.out.println(key + " - " + value);
 			}
		}
 		
	}
}

3) Sample Property File

How to Convert Properties to Map in Java

Output

first.name – Dinesh
second.name – Krishnan
email – [email protected]
full.name – Dinesh Krishnan
country – India

References

1. Java Properties Class
2. Java Map Interface
3. Java HashMap Class
4. Java File Class
5. Java FileReader Class
6. Java Set Interface
7. Java Iterator Interface