0
0
Kotlinprogramming~15 mins

Iterating collections with forEach in Kotlin - Mini Project: Build & Apply

Choose your learning style9 modes available
Iterating collections with forEach
📖 Scenario: You are helping a small bookstore manage its inventory. You have a list of book titles and want to print each title to check the stock.
🎯 Goal: Learn how to use the forEach function in Kotlin to go through each item in a list and print it.
📋 What You'll Learn
Create a list of book titles with exact values
Create a variable to count the number of books
Use forEach to print each book title
Print the total number of books after listing them
💡 Why This Matters
🌍 Real World
Bookstores and libraries often need to list and count their inventory. Using <code>forEach</code> helps to process each item easily.
💼 Career
Knowing how to iterate collections is essential for many programming jobs, especially when working with data lists or user inputs.
Progress0 / 4 steps
1
Create a list of book titles
Create a list called books with these exact titles: "The Hobbit", "1984", "Pride and Prejudice", "To Kill a Mockingbird"
Kotlin
Need a hint?

Use listOf to create a list with the given book titles.

2
Create a variable to count books
Create a variable called bookCount and set it to the size of the books list
Kotlin
Need a hint?

Use the size property of the list to get the number of books.

3
Use forEach to print each book title
Use books.forEach with a lambda that takes a parameter called book and prints it
Kotlin
Need a hint?

Use forEach with a lambda that prints each book.

4
Print the total number of books
Write a println statement that prints exactly: Total books: 4 using the bookCount variable inside an f-string
Kotlin
Need a hint?

Use println("Total books: $bookCount") to show the total count.