0% found this document useful (0 votes)
3 views5 pages

Worksheet 2 1

This document is a worksheet for a practical assignment in Mobile Application Development, focusing on Kotlin programming. It includes objectives and code examples for sorting a map by values, converting between lists and arrays, and calculating the difference between two time periods using Kotlin's LocalTime and Duration classes. The document outlines the procedures, algorithms, and expected learning outcomes for each task.

Uploaded by

ahhhhhhaahhhh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views5 pages

Worksheet 2 1

This document is a worksheet for a practical assignment in Mobile Application Development, focusing on Kotlin programming. It includes objectives and code examples for sorting a map by values, converting between lists and arrays, and calculating the difference between two time periods using Kotlin's LocalTime and Duration classes. The document outlines the procedures, algorithms, and expected learning outcomes for each task.

Uploaded by

ahhhhhhaahhhh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 5

Worksheet No.

– 2

Student Name: Anshul Gupta UID: 24MCA20490


Branch: MCA Section/Group: 5B
Semester: 2nd Date:- 03.02.2025
Subject Name: Mobile Application Development Subject Code: 24CAH-653

Aim/Overview of the practical:

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

val sortedMap = map.entries.sortedBy { it.value }

println("Map sorted by values (ascending):")

for (entry in sortedMap) { println("$

{entry.key} -> ${entry.value}")

val sortedMapDescending = map.entries.sortedByDescending { it.value }

println("\nMap sorted by values (descending):")

for (entry in sortedMapDescending)

{ println("${entry.key} -> $

{entry.value}")

Explanation:

 Step 1: The program defines a map with some sample key-value pairs.

 Step 2: The map.entries returns a set of map entries (Map.Entry).


 Step 3: sortedBy { it.value } sorts the entries based on the values in ascending order.
If you want descending order, you can use sortedByDescending { it.value }.

 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() {

// Step 1: Convert List (ArrayList) to Array

val arrayList = arrayListOf("apple", "banana", "cherry", "date")

println("Original ArrayList: $arrayList")

// Convert ArrayList to Array

val arrayFromList: Array<String> = arrayList.toArray(arrayOf())

println("Converted Array: ${arrayFromList.joinToString(", ")}")

// Step 2: Convert Array to List (ArrayList)

val array = arrayOf("apple", "banana", "cherry", "date")

println("\nOriginal Array: ${array.joinToString(", ")}")

// Convert Array to ArrayList

val listFromArray: ArrayList<String> = array.toCollection(ArrayList())

println("Converted ArrayList: $listFromArray")

Explanation:

 Convert ArrayList to Array:


 The toArray() function is used to convert the ArrayList to an Array. Since toArray()
returns a generic array, we provide an empty array of the required type as an
argument (arrayOf()).
 Convert Array to ArrayList:
 The toCollection() function is used to convert an Array to an ArrayList. Here, we specify
ArrayList<String>() as the target collection type.

Q3. Using class a Kotlin program to Calculate Difference Between two Time Periods. Code:

import java.time.LocalTime import

java.time.Duration

class TimePeriod(private val startTime: LocalTime, private val endTime: LocalTime)

{ fun calculateDifference(): String {

val duration = Duration.between(startTime, endTime) val

hours = duration.toHours()

val minutes = duration.toMinutes() % 60 val

seconds = duration.seconds % 60

return "Difference: $hours hours, $minutes minutes, $seconds seconds"

} }

fun main() {

val startTime = LocalTime.of(8, 30, 0) // 8:30 AM

val endTime = LocalTime.of(11, 45, 15) // 11:45:15 AM val

timePeriod = TimePeriod(startTime, endTime)

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:

 Understanding LocalTime and Duration Classes:


 You will learn how to use Kotlin’s LocalTime class, which is part of the java.time
package, to represent time without the need for a date.
 You'll also get familiar with the Duration class to compute the difference between two
LocalTime objects in terms of hours, minutes, and seconds.
 Using Classes and Methods in Kotlin:
 You will understand how to define and use classes in Kotlin, how to pass arguments
to constructors, and how to define methods to perform specific tasks.
 You’ll learn how to return meaningful results from class methods, such as the
difference between two time periods.
 Converting Between Time Units:
 You will gain the ability to convert and extract different units of time (e.g.,
hours, minutes, seconds) from a Duration object, which helps in calculating
precise time differences.
 Practical Application of Time Calculations:
 You’ll understand how to apply these concepts to real-world scenarios where time
differences are important, such as calculating the duration between events or
working hours.
 Kotlin Syntax and Features:
 By implementing this solution, you will reinforce your knowledge of Kotlin syntax
for defining classes, using constructors, and manipulating dates and times in Kotlin.
 You will also learn how Kotlin’s interoperability with Java libraries (like java.time) can
be leveraged to handle time calculations efficiently.

You might also like