How do I use ranges and step values in Kotlin for loops?

In Kotlin, you can use ranges and step values in for loops to iterate over a sequence of numbers or characters. Here’s a detailed guide:

1. Ranges in Kotlin

A range is defined using the .. operator. For example:

for (i in 1..5) {
    println(i)
}
  • Output: 1 2 3 4 5
  • The loop iterates from 1 to 5 (both inclusive).

2. Stepping Through a Range

To define the step value, you can use the step function. For instance:

for (i in 1..10 step 2) {
    println(i)
}
  • Output: 1 3 5 7 9
  • The loop starts from 1 and increments by 2 on each iteration.

3. Descending Ranges

If you want to iterate in reverse order, use the downTo function:

for (i in 10 downTo 1) {
    println(i)
}
  • Output: 10 9 8 7 6 5 4 3 2 1

You can combine downTo with step:

for (i in 10 downTo 1 step 2) {
    println(i)
}
  • Output: 10 8 6 4 2

4. Iterating Over Characters

Kotlin ranges also work with characters:

for (ch in 'a'..'e') {
    println(ch)
}
  • Output: a b c d e

You can also provide a step value:

for (ch in 'a'..'z' step 3) {
    println(ch)
}
  • Output: a d g j m p s v y

5. Using until

The until function creates a range that excludes the upper boundary:

for (i in 1 until 5) {
    println(i)
}
  • Output: 1 2 3 4
  • The loop stops before reaching 5.

Summary of Functions and Keywords

  1. ..: Creates a range that includes the start and end values.
  2. downTo: Creates a descending range.
  3. step: Sets the step value for the range.
  4. until: Excludes the upper boundary of the range.

These features make Kotlin’s for loops flexible and expressive.

How do I loop through items using for and while in Kotlin?

In Kotlin, you can use both for and while loops to iterate through items. Here is a quick overview of how you can use these loops with examples:


1. Using a for Loop

A for loop is used to iterate through a range, array, list, or any iterable.

Iterating through a range:

for (i in 1..5) {
    println("Current number is $i")
}
  • 1..5 creates a range from 1 to 5 (inclusive).
  • You can also use until to exclude the end value:
for (i in 1 until 5) {
    println("Current number is $i") // 1 to 4
}
  • To iterate in reverse, use the downTo keyword:
for (i in 5 downTo 1) {
    println("Countdown: $i")
}
  • To skip steps, use the step keyword:
for (i in 1..10 step 2) {
    println("Step: $i")
}

Iterating through a list or array:

val items = listOf("Apple", "Banana", "Orange")
for (item in items) {
    println(item)
}

Iterating with index:

val items = arrayOf("A", "B", "C")
for ((index, value) in items.withIndex()) {
    println("Index: $index, Value: $value")
}

2. Using a while Loop

A while loop is used when you want to execute a block of code as long as a condition is true.

Example of a while loop:

var counter = 1
while (counter <= 5) {
    println("Count: $counter")
    counter++
}

Example of a do-while loop:

The do-while loop ensures the block of code executes at least once.

var counter = 1
do {
    println("Count: $counter")
    counter++
} while (counter <= 5)

Summary of Differences:

  • for Loop: Best for iterating over ranges, collections, and when the number of iterations is known.
  • while (and do-while) Loop: Best for scenarios where the number of iterations depends on a condition.

How do I iterate through date range in Java?

The following code snippet shows you how to iterate through a range of dates in Java. We use the Java Date Time API. We do increment and decrement iteration using a simple for loop.

Here are the steps:

  • We declare the start and end date of the loop, the dates are instance of java.time.LocalDate.
  • Create a for loop.
  • In the for loop we set the initialization variable the start date.
  • The loop executed if the date is less than end date, using the isBefore() method, otherwise it will be terminated.
  • The date will be incremented by 1 on each loop.
package org.kodejava.datetime;

import java.time.LocalDate;
import java.time.format.TextStyle;
import java.util.Locale;

public class DateIteration {
    public static void main(String[] args) {
        LocalDate start = LocalDate.of(2023, 10, 1);
        LocalDate end = LocalDate.of(2023, 10, 8);

        System.out.println("Start = " + start);
        System.out.println("End   = " + end);
        System.out.println("--------------------");

        for (LocalDate date = start; date.isBefore(end); date = date.plusDays(1)) {
            System.out.printf("Date %tD is %s%n", date, date.getDayOfWeek());
        }

        System.out.println("--------------------");

        for (LocalDate date = end; date.isAfter(start); date = date.minusDays(1)) {
            System.out.printf("Date %tD is %s%n", date, date.getDayOfWeek()
                    .getDisplayName(TextStyle.SHORT, Locale.getDefault()));
        }
    }
}

Running the code snippet gives you the following output:

Start = 2023-10-01
End   = 2023-10-08
--------------------
Date 10/01/23 is SUNDAY
Date 10/02/23 is MONDAY
Date 10/03/23 is TUESDAY
Date 10/04/23 is WEDNESDAY
Date 10/05/23 is THURSDAY
Date 10/06/23 is FRIDAY
Date 10/07/23 is SATURDAY
--------------------
Date 10/08/23 is Sun
Date 10/07/23 is Sat
Date 10/06/23 is Fri
Date 10/05/23 is Thu
Date 10/04/23 is Wed
Date 10/03/23 is Tue
Date 10/02/23 is Mon

Next, we are going to use while loop.

  • Define the start and end date to loop
  • We increment the start date by 1 day.
  • Execute the loop if the start date is before end date.
package org.kodejava.datetime;

import java.time.LocalDate;

public class WhileDateIteration {
    public static void main(String[] args) {
        LocalDate start = LocalDate.of(2023, 10, 1).minusDays(1);
        LocalDate end = LocalDate.of(2023, 10, 8);

        while ((start = start.plusDays(1)).isBefore(end)) {
            System.out.printf("Date %tD is %s%n", start, start.getDayOfWeek());
        }
    }
}

The result of the code snippet above is:

Date 10/01/23 is SUNDAY
Date 10/02/23 is MONDAY
Date 10/03/23 is TUESDAY
Date 10/04/23 is WEDNESDAY
Date 10/05/23 is THURSDAY
Date 10/06/23 is FRIDAY
Date 10/07/23 is SATURDAY

To use the Java stream, we can do it like the following code snippet:

package org.kodejava.datetime;

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.stream.Stream;

public class StreamDateIteration {
    public static void main(String[] args) {
        LocalDate start = LocalDate.of(2023, 10, 1);
        LocalDate end = LocalDate.of(2023, 10, 8);

        Stream.iterate(start, date -> date.plusDays(1))
                .limit(ChronoUnit.DAYS.between(start, end))
                .forEach(date -> {
                    System.out.printf("Date %tD is %s%n", date, date.getDayOfWeek());
                });
    }
}

The result of the code snippet above is:

Date 10/01/23 is SUNDAY
Date 10/02/23 is MONDAY
Date 10/03/23 is TUESDAY
Date 10/04/23 is WEDNESDAY
Date 10/05/23 is THURSDAY
Date 10/06/23 is FRIDAY
Date 10/07/23 is SATURDAY

From Java 9 we can use LocalDate.datesUntil() method. It will iterate from the date to the specified end date by increment step of 1 day or the specified increment of Period.

package org.kodejava.datetime;

import java.time.LocalDate;
import java.time.Period;

public class DatesUntilDateIteration {
    public static void main(String[] args) {
        LocalDate start = LocalDate.of(2023, 10, 1);
        LocalDate end = LocalDate.of(2023, 10, 8);

        start.datesUntil(end).forEach(date -> {
            System.out.printf("Date %tD is %s%n", date, date.getDayOfWeek());
        });

        start.datesUntil(end, Period.ofDays(2)).forEach(System.out::println);
    }
}

Running the code snippet produces the following result:

Date 10/01/23 is SUNDAY
Date 10/02/23 is MONDAY
Date 10/03/23 is TUESDAY
Date 10/04/23 is WEDNESDAY
Date 10/05/23 is THURSDAY
Date 10/06/23 is FRIDAY
Date 10/07/23 is SATURDAY
2023-10-01
2023-10-03
2023-10-05
2023-10-07

How do I use for-each to iterate generic collections?

In this example you will learn you to iterate a generic collection using the for-each loop. There was actually no for-each keyword or statement in Java. It just a special syntax of the for loop. The structure or syntax of the for-each loop is as follows.

for (type var : collections) {
    body;
}

This form of for loop is always read as foreach and the colon (:) character is read as “in”. Given that definition, if the type is a String you will read the syntax above as “foreach String var in collections”. The var in the statement above will be given each value from the collections during the iteration process.

Let’s compare two codes, the first one that use a generic and another code that does not use a generic so we can see the difference from the iteration perspective when working with a collection.

package org.kodejava.generics;

import org.kodejava.generics.support.Customer;

import java.util.ArrayList;
import java.util.List;

public class ForEachGeneric {

    public void loopWithoutGeneric() {
        List customers = new ArrayList();
        customers.add(new Customer());
        customers.add(new Customer());
        customers.add(new Customer());

        for (int i = 0; i < customers.size(); i++) {
            Customer customer = (Customer) customers.get(i);
            System.out.println(customer.getFirstName());
        }
    }

    public void loopWithGeneric() {
        List<Customer> customers = new ArrayList<>();
        customers.add(new Customer());
        customers.add(new Customer());
        customers.add(new Customer());

        for (Customer customer : customers) {
            System.out.println(customer.getFirstName());
        }
    }
}

What you see from the code snippet above is how much more clean our code is when we are using the generic version of the collection. In the first method, the loopWithoutGeneric we have to manually cast the object back to the Customer type. But in the second method, the loopWithGeneric method, no cast is needed as the collection will return the same type as what the collection was declared to hold.