Kotlin Tutorials

Kotlin Map toProperties()
Syntax & Examples

Syntax of Map.toProperties()

The syntax of Map.toProperties() extension function is:

fun Map<String, String>.toProperties(): Properties

This toProperties() extension function of Map converts this Map to a Properties object.



✐ Examples

1 Convert a map to Properties

In this example,

  • We create a map named map1 containing key-value pairs "key1" to "value1" and "key2" to "value2".
  • We use the toProperties() extension function to convert map1 to a Properties object.
  • The resulting Properties object contains the key-value pairs from the map.
  • We print the Properties object to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val map1 = mapOf("key1" to "value1", "key2" to "value2");
    val properties = map1.toProperties();
    println(properties);
}

Output

{key1=value1, key2=value2}

2 Convert another map to Properties

In this example,

  • We create a map named map2 containing key-value pairs "name" to "John Doe" and "age" to "30".
  • We use the toProperties() extension function to convert map2 to a Properties object.
  • The resulting Properties object contains the key-value pairs from the map.
  • We print the Properties object to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val map2 = mapOf("name" to "John Doe", "age" to "30");
    val properties = map2.toProperties();
    println(properties);
}

Output

{name=John Doe, age=30}

3 Convert a map of location to Properties

In this example,

  • We create a map named map3 containing key-value pairs "city" to "New York" and "country" to "USA".
  • We use the toProperties() extension function to convert map3 to a Properties object.
  • The resulting Properties object contains the key-value pairs from the map.
  • We print the Properties object to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val map3 = mapOf("city" to "New York", "country" to "USA");
    val properties = map3.toProperties();
    println(properties);
}

Output

{country=USA, city=New York}

Summary

In this Kotlin tutorial, we learned about toProperties() extension function of Map: the syntax and few working examples with output and detailed explanation for each example.