Kotlin – Convert Map to/from Properties

In the post, we show how to convert ‘Kotlin Map to Properties’ and versus case ‘Properties to Kotlin Map’.

I. Kotlin – Convert Map to Properties

Use toProperties() method of Map class,
-> Method signature:


fun Map.toProperties(): Properties

Practice:


package com.javasampleapproach.kotlin.map2properties

fun main(args: Array) {
	val map = mutableMapOf()
	map.put("db.username", "username")
	map.put("db.password", "password")
	map.put("db.driver", "org.postgresql.Driver")
	map.put("db.url", "jdbc:postgresql://localhost/testdb")
	
	// Converts this [Map] to a [Properties] object.
	// use -> fun Map.toProperties(): Properties
	val propertiesOfMap = map.toProperties()
	
	// Traverse through propertiesOfMap
	propertiesOfMap.forEach{(k, v) -> println("key=$k, value=$v")}
	/*
		key=db.password, value=password
		key=db.url, value=jdbc:postgresql://localhost/testdb
		key=db.username, value=username
		key=db.driver, value=org.postgresql.Driver
	 */
}

II. Kotlin – Convert Properties to Map

Iterate through Properties object by forEach or for-loop statement then manually use put(key: K, value: V) method of Map interface.

Practice:


package com.javasampleapproach.kotlin.properties2map

import java.util.Properties

/*
	Convert Properties to Map
 */
fun main(args: Array) {
	val properties = Properties();
	val mapOfProperties = mutableMapOf()
	
	properties.put("db.username", "username");
	properties.put("db.password", "password");
	properties.put("db.driver", "org.postgresql.Driver");
	properties.put("db.url", "jdbc:postgresql://localhost/testdb");
	
	// 1.
	// --> use properties.forEach
	properties.forEach{(k, v) -> mapOfProperties.put(k.toString(), v.toString())}
	
	// Traverse Through mapOfProperties
	mapOfProperties.forEach{(k, v) -> println("key=$k, value=$v")}
	/*
		key=db.password, value=password
		key=db.url, value=jdbc:postgresql://localhost/testdb
		key=db.username, value=username
		key=db.driver, value=org.postgresql.Driver
 	*/
	
	println("--------------------------------------")
	
	// 2.
	// --> use forLoop
	mapOfProperties.clear()
	
	for((k, v) in properties){
		mapOfProperties.put(k.toString(), v.toString())
	}
	
	// Traverse Through mapOfProperties
	mapOfProperties.forEach{(k, v) -> println("key=$k, value=$v")}
	/*
		key=db.password, value=password
		key=db.url, value=jdbc:postgresql://localhost/testdb
		key=db.username, value=username
		key=db.driver, value=org.postgresql.Driver
 	*/
}


By grokonez | March 4, 2018.

Last updated on April 27, 2021.



Related Posts


Got Something To Say:

Your email address will not be published. Required fields are marked *

*