Showing posts with label Kotlin Conversions. Show all posts
Showing posts with label Kotlin Conversions. Show all posts

Monday, June 14, 2021

Kotlin - Convert Map to List Examples

1. Overview

In this tutorial, We will learn how to convert the Map to List in kotlin programming. Map implementations such as HashMap or TreeMap can be converted into an ArrayList or List object.

Let us explore the different ways to do conversion from map to get the list of keys and values.

Kotlin - Convert Map to List Examples



2. Converting HashMap to List in Kotlin Using ArrayList Constructor


This approach is the simple one and easy. First create the HashMap object with HashMap() constructor
Next, adding few key value pairs to the map. Use map.keys and map.values to get the all keys and values.
pass these values to ArrayList constructor to convert the map to list.

These properties will be invoking the below functions internally when you are using java.util.HashMap.

map.keys --> map.keySet()
map.values --> map.values()

package com.javaprogramto.kotlin.collections.map.list

import java.util.HashMap

fun main(array: Array<String>) {

    var map = HashMap<Int, String>();

    map.put(10, "Ten")
    map.put(20, "Twenty")
    map.put(30, "Thirty")
    map.put(40, "Fourty")
    map.put(50, "Fifty")

    var keysList = ArrayList(map.keys);
    var valuesList = ArrayList(map.values);

    println("Keys list : $keysList")
    println("Values list : $valuesList")

}

Output:
Keys list : [50, 20, 40, 10, 30]
Values list : [Fifty, Twenty, Fourty, Ten, Thirty]

3. Converting LinkedHashMap to List in Kotlin Using ArrayList Constructor


From the above program, the output is not in the order what is inserted into the map. To preserve the insertion order then need to use LinkedHashMap class instead of HashMap.

Look at the below program and observer the output order.

package com.javaprogramto.kotlin.collections.map.list

import java.util.HashMap

fun main(array: Array<String>) {

    // to holds the insertion order
    var map = LinkedHashMap<Int, String>();

    map.put(10, "Ten")
    map.put(20, "Twenty")
    map.put(30, "Thirty")
    map.put(40, "Fourty")
    map.put(50, "Fifty")

    // gets the keys and values as per the insertion
    var keysList = ArrayList(map.keys);
    var valuesList = ArrayList(map.values);

    // prints
    println("Keys list : $keysList")
    println("Values list : $valuesList")
}
Output:
Keys list : [10, 20, 30, 40, 50]
Values list : [Ten, Twenty, Thirty, Fourty, Fifty]


4. Kotlin Map to List using toList() method


Use toList() method on map object or keys, values properties.

package com.javaprogramto.kotlin.collections.map.list
import java.util.HashMap

fun main(array: Array<String>) {

    var map = HashMap<Int, String>();

    map[10] = "Ten"
    map[20] = "Twenty"
    map[30] = "Thirty"
    map[40] = "Fourty"
    map[50] = "Fifty"

    // example 1 using toList() method
    var keysList = map.keys.toList();
    var valuesList = map.values.toList();
    println("using toList()")
    println("Keys list : $keysList")
    println("Values list : $valuesList")

    // example 2 using toList() method

    var mutableMap: MutableMap<Int, String> = HashMap()
    mutableMap[10] = "Ten"
    mutableMap[20] = "Twenty"
    mutableMap[30] = "Thirty"
    mutableMap[40] = "Fourty"
    mutableMap[50] = "Fifty"

    var entries = mutableMap.toList().map { "(${it.first}, ${it.second})"}
    println("\nusing toList() on mutable map")
    entries.forEach{print("$it ")}
}

Output:

using toList()
Keys list : [50, 20, 40, 10, 30]
Values list : [Fifty, Twenty, Fourty, Ten, Thirty]

using toList() on mutable map
(50, Fifty) (20, Twenty) (40, Fourty) (10, Ten) (30, Thirty) 

5. Kotlin Map to List using entries properties


map.entries properties will returns the key-value pairs. Use map() method  on the entries object.  We can use the any pattern in between the key and value.

package com.javaprogramto.kotlin.collections.map.list

import java.util.HashMap

fun main(array: Array<String>) {

    var mutableMap: MutableMap<Int, String> = HashMap()

    mutableMap[10] = "Ten"
    mutableMap[20] = "Twenty"
    mutableMap[30] = "Thirty"
    mutableMap[40] = "Fourty"
    mutableMap[50] = "Fifty"

    var list : List<String> = mutableMap.entries.map { ("${it.key} -->  ${it.value}") }

    list.forEach{println(it)}
}

Output:

50 -->  Fifty
20 -->  Twenty
40 -->  Fourty
10 -->  Ten
30 -->  Thirty

6. Kotlin Map to List using keys and values


Use keys and values properties of map object to call map() method.

package com.javaprogramto.kotlin.collections.map.list

import java.util.HashMap

fun main(array: Array<String>) {

    var mutableMap: MutableMap<Int, String> = HashMap()

    mutableMap[10] = "Ten"
    mutableMap[20] = "Twenty"
    mutableMap[30] = "Thirty"
    mutableMap[40] = "Fourty"
    mutableMap[50] = "Fifty"

    var keysList : List<String> = mutableMap.keys.map { ("${it} ") }
    var valuesList : List<String> = mutableMap.values.map { ("${it} ") }

    println("---- keys list ------")
    keysList.forEach{println(it)}

    println("----- values list ------")
    valuesList.forEach{println(it)}
}

Output:

---- keys list ------
50 
20 
40 
10 
30 
----- values list ------
Fifty 
Twenty 
Fourty 
Ten 
Thirty 

7. Conclusion


in this article, We have seen how to convert Map to List in Kotlin programming and examples on different approaches.



Thursday, January 7, 2021

How To Convert String to Float in Kotlin?

1. Overview

In this tutorial, We will learn how to convert the String value to Float in Kotlin. This conversion is done using toFloat() method of String class.

But there are many cases where it gives parsing errors for wrong inputs.

How To Convert String to Float in Kotlin?


2. Kotlin String to Float using toFloat() Method

Converting string to float is done with toFloat() method of string class.

toFloat() method is to parse the String value into Float. If the string is not a valid form of a number or any non-number presents then it throws NumberFormatException.


package com.javaprogramto.kotlin.conversions

fun main(args: Array<String<) {

    var str : String = "12345.678"
    var float1 : Float = str.toFloat();
    println("string to float - float1 $float1")

    var str2 : String = "A123"
    var float2 : Float = str2.toFloat();
    println("string to float - float2 $float2")
    
}


Output:


string to float - float1 12345.678
Exception in thread "main" java.lang.NumberFormatException: For input string: "A123"
	at java.base/jdk.internal.math.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2054)
	at java.base/jdk.internal.math.FloatingDecimal.parseFloat(FloatingDecimal.java:122)
	at java.base/java.lang.Float.parseFloat(Float.java:461)
	at com.javaprogramto.kotlin.conversions.StringToFloatExampleKt.main(StringToFloatExample.kt:10)


3. Kotlin String to Float using toFloatOrNull() Method

Next, use the another method for string to float conversion if the input string is not a valid number.

Call toFloatOrNull() method to get the null value if the string is having at least one non-digit.

Method toFloatOrNull() will convert String to Float.


package com.javaprogramto.kotlin.conversions

fun main(args: Array<String>) {

    var str : String = "456.75F"
    var float3 = str.toFloatOrNull();
    println("string to float - float3 $float3")

    var str2 : String = "PI3.14"
    var float4 = str2.toFloatOrNull();
    println("string to float - float4 $float4")
}


Output:

string to float - float3 456.75
string to float - float4 null


Note: When you are calling the toFloatOrNull() method, you should not specify the type to hold the value like var float3 : Float = str.toFloatOrNull(). This will give the compile error "Kotlin: Type mismatch: inferred type is Float? but Float was expected"


4. Conclusion

In this article, We've seen how to convert the string values into Float in Kotlin. And also how to handle if the string is containing the characters other than numbers.

GitHub

Kotlin Ternary Operator


Tuesday, January 5, 2021

Kotlin - Convert List to Map Examples

1. Overview

In this tutorial, We'll learn how to convert the List to Map in Kotlin programming. Let us explore the different ways to do this conversion.

Kotlin provides a set of methods for the functionality.

  • associate()
  • associateBy()
  • map() and toMap()
  • Running for loop and set to map
First created a Website class with site name and its rank value. Next, Created and added 4 objects to list.

Converting the List to Map is shown in the below sections with example programs.

Kotlin - Convert List to Map Examples



2. Kotlin List to Map with associate() method


Use associate() method to convert the List of object to Map with the needed type for key, value pairs.

Pass the Pair() object with the key, value pair object and internally it iterates over the loop.

package com.javaprogramto.kotlin.collections.list.map

data class Website(var site: String, var rank: Long);

fun main(args: Array<String>) {

    var websiteranks: List<Website> = listOf(
        Website("google.com", 1),
        Website("youtube.com", 2),
        Website("amazon.com", 3),
        Website("yahoo.com", 4)
    );

    println("List values : $websiteranks")

    val finalMap : Map<String, Long> = websiteranks.associate { Pair(it.site, it.rank) };

    println("Final map from list using associate : $finalMap")

    val mapValueCustomType : Map<String, Website> = websiteranks.associate { Pair(it.site, it) };
    println("Map value as custom type using associate : $mapValueCustomType")

}

Output:
List values : [Website(site=google.com, rank=1), Website(site=youtube.com, rank=2), Website(site=amazon.com, rank=3), Website(site=yahoo.com, rank=4)]
Final map from list using associate : {google.com=1, youtube.com=2, amazon.com=3, yahoo.com=4}
Map value as custom type using associate : {google.com=Website(site=google.com, rank=1), youtube.com=Website(site=youtube.com, rank=2), amazon.com=Website(site=amazon.com, rank=3), yahoo.com=Website(site=yahoo.com, rank=4)}

3. Kotlin List to Map with associateBy() method


Next, use the associateBy() method to convert list to map in another way.

package com.javaprogramto.kotlin.collections.list.map

fun main(args: Array<String>){
    var websiteranks: List<Website> = listOf(
        Website("google.com", 1),
        Website("youtube.com", 2),
        Website("amazon.com", 3),
        Website("yahoo.com", 4)
    );

    val finalMap : Map<String, Long> = websiteranks.associateBy({it.site}, {it.rank});

    println("Final map from list using associateBy: $finalMap")

    val mapValueCustomType : Map<String, Website> = websiteranks.associateBy({it.site}, {it})
    println("Map value as custom type using associateBy : $mapValueCustomType")

}

Output:

Final map from list using associateBy: {google.com=1, youtube.com=2, amazon.com=3, yahoo.com=4}
Map value as custom type using associateBy : {google.com=Website(site=google.com, rank=1), youtube.com=Website(site=youtube.com, rank=2), amazon.com=Website(site=amazon.com, rank=3), yahoo.com=Website(site=yahoo.com, rank=4)}


4. Kotlin List to Map with map() and toMap() methods


Next, use map() and toMap() methods on the list object.

map() method returns ArrayList.
toMap() method returns Map object.

package com.javaprogramto.kotlin.collections.list.map

// kotlin program to convert list to map using map() and toMap() methods.
fun main(args: Array<String>){
    var websiteranks: List<Website> = listOf(
        Website("google.com", 1),
        Website("youtube.com", 2),
        Website("amazon.com", 3),
        Website("yahoo.com", 4)
    );

    val finalMap : Map<Long, String> = websiteranks.map { it.rank to it.site }.toMap()

    println("Final map from list using map() and toMap() methods : $finalMap")

    val mapValueCustomType : Map<String, Website> = websiteranks.map{it.site to it}.toMap();
    println("Map value as custom type using map() and toMap() methods : $mapValueCustomType")

}

Output:
Final map from list using map() and toMap() methods : {1=google.com, 2=youtube.com, 3=amazon.com, 4=yahoo.com}
Map value as custom type using map() and toMap() methods : {google.com=Website(site=google.com, rank=1), youtube.com=Website(site=youtube.com, rank=2), amazon.com=Website(site=amazon.com, rank=3), yahoo.com=Website(site=yahoo.com, rank=4)}


5. Kotlin List to Map Using Loops


Finally, Look at the conversion to Map using for loops with normal iteration. In this way, we get the each value from list and set to a new map.

// kotlin program to convert list to map using for each loop
fun main(args: Array<String>) {
    var websiteranks: List<Website> = listOf(
        Website("google.com", 1),
        Website("youtube.com", 2),
        Website("amazon.com", 3),
        Website("yahoo.com", 4)
    );

    val finalMap: MutableMap<String, Long> = HashMap();

    for (website in websiteranks) {
        finalMap[website.site] = website.rank;
    }

    println("Map from list using custom iterating the list with for loop : $finalMap")

}

Output:
Map from list using custom iterating the list with for loop : {google.com=1, amazon.com=3, yahoo.com=4, youtube.com=2}

6. Conclusion


In this article, we have seen the different ways to do conversion from List to Map.

Among all methods, associate() method is the right choice and mostly used in the real time applications.
Next, use toMap() method if you are iterating the list and doing some other operations. 

But, toMap() method is more readable. 


Thursday, April 30, 2020

Kotlin Program to Convert a Stack Trace to a String

1. Introduction


In this article, You'll learn how to convert kotlin stack trace to a String programmatically. 

This is part of the Kotlin Program Series


Kotlin Program to Convert a Stack Trace to a String

Kotlin Program To Convert String to Date

1. Introduction


In this article, you'll learn how to convert String to Date in Kotlin. The string can be any valid date format but you should convert the String date format to an actual date object.

Example: 

String = "2020-05-01";
Converted Date: 2020-05-01 

A converted date is in a form of the Date object.

This is part of the Kotin Programming Series.


Kotlin Program To Convert String to Date

Tuesday, April 28, 2020

Kotlin Program to Convert List (ArrayList) to Array

1. Introduction


In this article, you'll learn how to convert List to Array in Kotlin.

This is part of the Kotlin Programming Series. Here you can find more programs in kotlin.

This can be done simply by calling the toArray() method on the collection object.

Kotlin Program to Convert List (ArrayList) to Array