https://grokonez.com/kotlin/kotlin-convert-map-tofrom-properties

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:

More at:

https://grokonez.com/kotlin/kotlin-convert-map-tofrom-properties

Kotlin – Convert Map to/from Properties

#kotlin #properties #map

Kotlin - Convert Map to/from Properties » grokonez
2.65 GEEK