Day52 of #100DaysOfCode

Kushagra Kesav
2 min readMar 30, 2022
#CodeTogether Day 52/100

Hii folks 🙌

Today I will be continuing the same lesson on the same pathway of Unit 3.

Unit 3: Navigation

Pathway 1: Navigate between screens

Source: https://developer.android.com/courses/android-basics-kotlin/course

Working with collections

Different types of collections have a lot of behavior in common. If they’re mutable, we can add or remove items. We can enumerate all the items, find a particular item, or sometimes convert one type of collection to another. We did this earlier when we converted a List to a Set with toSet(). Here are some more helpful functions for working with collections:

  • forEach
fun main() {
val peopleAges = mutableMapOf<String, Int>(
"Fred" to 30,
"Ann" to 23
)
peopleAges.put("Barbara", 42)
peopleAges.forEach { print("${it.key} is ${it.value}, ") }
}
Fred is 31, Ann is 23, Barbara is 42, Joe is 51
  • map
println(peopleAges.map { "${it.key} is ${it.value}" }.joinToString(", ") )Fred is 31, Ann is 23, Barbara is 42, Joe is 51
  • filter
val filteredNames = peopleAges.filter { it.key.length < 4 }
println(filteredNames)
{Ann=23, Joe=51}
  • Lambdas
fun main() {
val triple: (Int) -> Int = { a: Int -> a * 3 }
println(triple(5))
}
15
  • Higher-order functions
fun main() {
val peopleNames = listOf("Fred", "Ann", "Barbara", "Joe")
println(peopleNames.sorted())
println(peopleNames.sortedWith { str1: String, str2: String -> str1.length - str2.length })
}
[Ann, Barbara, Fred, Joe]
[Ann, Joe, Fred, Barbara]
  • We will make a word list from the above-learned concepts:
fun main() {
val words = listOf("about", "acute", "awesome", "balloon", "best", "brief", "class", "coffee", "creative")
val filteredWords = words.filter { it.startsWith("b", ignoreCase = true) }
.shuffled()
.take(2)
.sorted()
println(filteredWords)
}
[balloon, brief]

Today I Learned:

  • Kotlin provides many functions for processing and transforming collections, including forEach, map, filter, sorted, and more.
  • A lambda is a function without a name that can be passed as an expression immediately. An example would be { a: Int -> a * 3 }.
  • A higher-order function means passing a function to another function or returning a function from another function.

That is all for Day52 ✅

Thanks for reading, See you tomorrow!

If you are reading my #100Days Journey, feel free to drop by ;)

--

--