Java Tutorials for Freshers and Experience developers, Programming interview Questions, Data Structure and Algorithms interview Programs, Kotlin programs, String Programs, Java 8 Stream API, Spring Boot and Troubleshooting common issues.
Monday, December 20, 2021
Kotlin Program to Join Two Lists
Monday, June 14, 2021
Kotlin - Convert Map to List Examples
1. Overview
2. Converting HashMap to List in Kotlin Using ArrayList Constructor
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") }
Keys list : [50, 20, 40, 10, 30] Values list : [Fifty, Twenty, Fourty, Ten, Thirty]
3. Converting LinkedHashMap to List in Kotlin Using ArrayList Constructor
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") }
Keys list : [10, 20, 30, 40, 50] Values list : [Ten, Twenty, Thirty, Fourty, Fifty]
4. Kotlin Map to List using toList() method
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 ")} }
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
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)} }
50 --> Fifty 20 --> Twenty 40 --> Fourty 10 --> Ten 30 --> Thirty
6. Kotlin Map to List using keys and values
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)} }
---- keys list ------ 50 20 40 10 30 ----- values list ------ Fifty Twenty Fourty Ten Thirty
7. Conclusion
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.
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.
Wednesday, January 6, 2021
Kotlin Variables and Basic Types With Examples - Kotlin Tutorial
1. Overview
2. Variable var examples
package com.javaprogramto.kotlin.variables fun main(args: Array<String>) { // double type var pi : Double = 3.14 println("Double PI value $pi") // without type but it takes the double type internally based on the value var doubleValue = 3.14; println("Default type double $doubleValue") // Without type but it takes as String type from assigned value var welcome = "hello world" println("string welcome note $welcome") var str : String = "i am string" println("string type note $str") }
Double PI value 3.14 Default type double : doubleValue string welcome note hello world string type note i am string
3. val Variable Examples
package com.javaprogramto.kotlin.variables fun main(args: Array<String>) { // int type varaible with var keyword var number: Int = 12345; println("old value of number : $number") number = 10000 println("new value of number : $number") // int type variable with val keyword val highestMark: Int = 99; println("old value of highestMark : $number") highestMark = 98 println("new value of highestMark : $number") }
Kotlin: Val cannot be reassigned
4. Difference between var and val
5. Assigning the large numbers to variables
package com.javaprogramto.kotlin.variables fun main(args: Array<String>) { // long numbers with underscore for readable var creditCardNumber: Long = 4320_3456_9808_4389 var debitCardNumber = 1234_45678_1234_9876L var timeInMilliSeconds = 60_000 // printing println("Credit card number : $creditCardNumber") println("Debit card number : $debitCardNumber") println("Time in milli seconds : $timeInMilliSeconds") }
Credit card number : 4320345698084389 Debit card number : 12344567812349876 Time in milli seconds : 60000
6. Kotlin Variable With Null Values - Null Safe (?)
// declaring a variable with the null val noValue : String? // assigning value noValue = "assigned value" // printing the value println("novalue is now : $noValue")
novalue is now : assigned value
7. Type Conversions
var number1 : Int = 10; var number2 : Long = 12345678; // compile time error : Kotlin: Type mismatch: inferred type is Int but Long was expected // number2 = number1; // right conversion number2 = number1.toLong(); println("number 2 : $number2")
number 2 : 10
var number3 = 10; var number4= 12345678; // no compile time error number4 = number3; println("number4 : $number4")
number4 : 10
// variable with null type and value assignment var number5 : Int? = 100 var number6 : Long? = 200 // compile time error - Kotlin: Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type Int? // number6 = number5.toLong() // no error with null safe number6 = number5?.toLong(); println("number 6 : $number6")
number 6 : 100
8. Kotlin Basic Types
- Numbers
- Char
- Boolean
- Array
// Numbers // Byte : range -128 to 127 var byteVar: Byte = 100 println("Byte variable : $byteVar") // Short : range -32768 to 32767 var shortVar: Short = -1000 println("Short variable : $shortVar") // Int : range -2^31 to 2^31-1 var intVar: Int = 12345 println("Int variable : $intVar") // Long : range -2^63 to 2^63-1 var longVar: Long = 12345678900 println("Long variable : $longVar") // Float : single precision 32 bit float point var floatVar: Float = 123.4F // F is mandatory at end else compile time error println("Float variable : $floatVar") // Double : precision 64 bit floating value var doubleVar: Double = 1234.56 println("Double variable : $doubleVar") // Characters // Char var charVar: Char = 'A' println("Char variable : $charVar") // Boolean - this takes only two values - true/false var booleanVar: Boolean = true println("Boolean variable : $booleanVar") var booleanVarFalse: Boolean = false println("Boolean variable false : $booleanVarFalse") // Arrays // implicit type declaration var array1 = listOf(1,2,3,4,5) // explcit type declaration var array2 = listOf<Long>(1,2,3,4,5)
Byte variable : 100 Short variable : -1000 Int variable : 12345 Long variable : 12345678900 Float variable : 123.4 Double variable : 1234.56 Char variable : A Boolean variable : true Boolean variable false : false
9. Conclusion
Tuesday, January 5, 2021
Kotlin - Convert List to Map Examples
1. Overview
- associate()
- associateBy()
- map() and toMap()
- Running for loop and set to map
2. Kotlin List to Map with associate() method
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") }
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
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") }
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
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") }
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
// 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") }
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
Monday, August 10, 2020
Kotlin Program to Sort ArrayList of Custom Objects By Property
1. Introduction
This is part of the Kotlin Programming Series.
Thursday, April 30, 2020
Kotlin Program to Convert a Stack Trace to a String
1. Introduction
Kotlin Program To Convert String to Date
1. Introduction
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 Get Current Date and Time
1. Introduction
In this tutorial, You'll learn how to get the current date and time in kotlin. Further, you will see the examples how to get the default date and time, getting date in a specified pattern or format and also showing programs on locales.
Java : jdk1.8.0_251
Kotlin: 1.3
Popular Posts
- Adding/Writing Comments in Java, Comment types with Examples
- 3 Ways to Fix Git Clone "Filename too long" Error in Windows [Fixed]
- Java Program To Reverse A String Without Using String Inbuilt Function reverse()
- Java IS-A and HAS-A Relationship With Examples
- Java Thread.join() Examples to Wait for Another Thread