Worksheet 2 1
Worksheet 2 1
– 2
Kotlin Program to Sort a Map By Values. Kotlin Program to Convert List (Array List) to
Array and Vice-Versa. Using class a Kotlin program to Calculate Difference Between Two
Time Periods.
Objective:
Sort the Entries by Values:- The program demonstrates how to take a Map and sort it based
on the values of the entries, rather than the keys. Showcase Kotlin's Functional Features:-
By using functions like sorted By (or sortedByDescending for descending order), the
program illustrates Kotlin's functional programming features, which make it easy to sort
collections. Provide a Practical Solution:- This solution is useful in situations where you
need to organize or display data from a Map in order of value size, which could be relevant
for tasks such as ranking, prioritizing, or analyzing data.
Procedure/Algorithm/Code:-
Input: A map with keys and corresponding values.
Example: map = { "apple" -> 5, "banana" -> 2, "cherry" -> 8, "date" -> 3 }
Step 1: Extract the entries from the map using map.entries.
Entries will be of type Map.Entry<K, V>.
Step 2: Sort the entries by their values.
Use the sortedBy { it.value } function to sort the entries in ascending order by values.
Step 3: Store the sorted entries.
Store the sorted entries in a new list or collection.
Step 4: Output the sorted map.
Iterate over the sorted entries and print each key-value pair.
Output: The keys and values will be displayed in ascending order of values.
Q1. Kotlin Program to Sort a Map By Values.
Code:
fun main() {
val map =
mapOf( "apple" to 5,
"banana" to 2,
"cherry" to 8,
"date" to 3
{ println("${entry.key} -> $
{entry.value}")
Explanation:
Step 1: The program defines a map with some sample key-value pairs.
Step 4: The sorted entries are then printed, showing the keys and their corresponding
values in the new order.
Q2. Kotlin Program to Convert List (ArrayList) to Array and Vice-Versa. Code:
fun main() {
Explanation:
Q3. Using class a Kotlin program to Calculate Difference Between two Time Periods. Code:
java.time.Duration
hours = duration.toHours()
seconds = duration.seconds % 60
} }
fun main() {
println(timePeriod.calculateDifference())
Explanation:
TimePeriod Class:
The class TimePeriod accepts two LocalTime values: startTime and endTime.
The calculateDifference() function calculates the duration between these two LocalTime
instances using Duration.between().
It then extracts the difference in hours, minutes, and seconds from the Duration.
Main Function:
Two LocalTime objects are created (startTime and endTime).
An instance of the TimePeriod class is created with the given start and end times.
The difference between the two times is
printed. Learning Outcomes: