Pages

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

Monday, December 20, 2021

Kotlin Program to Join Two Lists

1. Introduction


In this article, You'll learn how to join two lists in kotlin programming language. List API has addAll() method and apache ListUtils.union() method to add two lists in kotlin.

First, we'll see the example program with built-in api method addAll() and next further using ListUtils.union() method from apache commons api.

Kotlin Program to Join Two Lists



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


Wednesday, January 6, 2021

Kotlin Variables and Basic Types With Examples - Kotlin Tutorial

1. Overview

In this tutorial, We will learn how to create the variables in Koltin for basic types using var.

var is a keyword in kotlin which is used to declare the any type of variable.

Kotlin has another keyword "val" to declare the variables.

Any variable is declared using var that value can be changed at anytime whereas variable declared with val keyword value can not modified one it is initialized.

Mainly val is used to define the constants in kotlin.

Kotlin Variables and Basic Types



2. Variable var examples


var keyword is used in the variable declaration. When you are using var keyword, that indicates the value can be changed at any time and the variable type is optional. If we are not provided the type then it takes the type implicitly based on the value assigned.

Syntax:

var <variable-name> : <variable-type-optional> = value;

Examples:

Below are the few examples on with and without variable type.

First created a double variable with var keyword with 3.14 value. Next used only var and did not mention any type but assigned the value. So it takes it as double internally because value is double type.

Additionally, created a variable with string content and not mentioned its type. But, kotlin has the intelligence to inspect the value and assign the right type.

if you call the welcome.toUpperCase() method, it does not throw any error. because it knows that object is type of String. So, We can use all methods from String class.

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")
}

Output:
Double PI value 3.14
Default type double : doubleValue
string welcome note hello world
string type note i am string

3. val Variable Examples


val is an another keyword in koltin and it is alos used to declare the variables.

Let us create a variable and try to change the value to new one using var and val variables.

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")
}


Output:
Kotlin: Val cannot be reassigned

It will produce the compile time error saying value can not be reassigned for val type variable.

So, val keyword is only to declare the constant values because it will not allow to change the value.

4. Difference between var and val


The main difference between the val and var keywords - is var type variables values can be modified and reassigned with the new values but val type variables can not be reassigned with the new values.

5. Assigning the large numbers to variables


When you are using the kotlin in the real time applications, there will be a need to hold the credit card or debit card numbers and phone numbers. 

var creditCardNumber : Long = 4320123456782468;

The above number is not readable but it holds the actual value. To make the numbers more readable, we can use the underscore(_) delimiter in between the numbers.

We can use the underscore for any numbers even it is good to use for currency values or time values.

but when you print or use for different operations, it does not print or get error because of underscore usage. It removes the underscore while performing any mathematical operations. This delimiter just makes the data readable form.

Look the below example for better understanding.

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")
}

Output:

Credit card number : 4320345698084389
Debit card number : 12344567812349876
Time in milli seconds : 60000

6. Kotlin Variable With Null Values - Null Safe (?)


As of now, we have seen the variable declaration and its initialization in single line. But now you want to do only the declaration with null value.

Now, how can we create a variable with null value in kotlin?

Use the ? symbol at the end of the variable declaration to assign with null value. Look at the below syntax.

val/var <variable-name> : <variable-type-optional> ?;

Sample example program to show variable nullable.

 // declaring a variable with the null
 val noValue : String?

 // assigning value
 noValue = "assigned value"

 // printing the value
 println("novalue is now : $noValue")

Output:

novalue is now : assigned value


Note: We can not use the null variable without initializing to a value. It show the compile time error "Kotlin: Variable 'noValue' must be initialized"

7. Type Conversions


Next, let us focus on the type conversions in kotlin.

We will try to convert Int to Long value without any casting. Just assign the Int variable to Long variable.

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")

Output:

number 2 : 10

In the above program first directly assigned the int value to the long value but it give compile time error.

Kotlin does not support the direct assignment conversions when the type is mentioned in the declaration. Use toLong() method to do the explicit conversion from Int to Long. This is the process to convert from any type to any type in kotlin.

If the type is not mentioned in the declaration then it is allowed for direct assignment conversion.

var number3 = 10;
var number4= 12345678;

// no compile time error
 number4 = number3;

println("number4 : $number4")

Output:

number4 : 10

Type conversion with nullable type:

When you are using the nullable value type (?) in the declaration then you must use always the variable usage.

Use the null safe(?) operator when calling methods on the variable otherwise will get the compile time error.

// 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")

Output:

number 6 : 100

8. Kotlin Basic Types 


Kotlin has the basic type supports as similar to the Java.

  • Numbers
                Byte
                Short
                Int
                Long
                Float
                Double
  • Char
  • Boolean
  • Array

let us explore the different examples on how to create the numbers, characters, booleans and arrays type variables in kotlin.

// 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)

Output:
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


In this tutorial, we have seen how declare the variables example programs and other interesting stuff for kotlin programmers.


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. 


Monday, August 10, 2020

Kotlin Program to Sort ArrayList of Custom Objects By Property

1. Introduction


In this tutorial, you will learn how to sort the ArrayList of Custom objects and sort by their given property or field.

This is part of the Kotlin Programming Series.

First, We will see the example program to sort the custom class and next, how to sort the List of Employee objects.

Kotlin Program to Sort ArrayList of Custom Objects By Property

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

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

Kotlin Program to Get Current Date and Time


If you are new to Kotlin, you can set up Kotlin in Intelleji Idea.