For Loops: Java vs Kotlin
A very quick for-loop variations in Java and Kotlin!
Loops are one of the most basic building block of any programming language. Irrespective of your language of choice, for loops or a variant of it is sure to exist. In that spirit, today I would like to do a side by side comparison of what for loops look like in two very popular JVM languages: Java and Kotlin.
Accessing elements directly
As an example let us consider a list of numbers that we need to iterate over and print.
In Java:
List<Integer> numbers = new ArrayList(){{
add(3);
add(6);
add(9);
add(12);
}};for(Integer number: numbers) {
System.out.println(number);
}
The Kotlin version of the code would be (dropping the type decleration as a part of the for loop):
val numbers = listOf(3, 6, 9, 12)for(number in numbers) {
println(number)
}
Output:
3
6
9
12
Accessing elements using the index
Having to access elements in a collection like an array or a list is probably programming 101.
In good old Java that would be:
List<Integer> numbers = new ArrayList(){{
add(3);
add(6);
add(9);
add(12);
}};for(int index=0; index<numbers.size(); index++) {
System.out.println(numbers.get(index));
}
Kotlin has support for ranges that we could for the index (note that both the bounds of the for loop are inclusive):
val numbers = listOf(3, 6, 9, 12)for(index in 0..numbers.size-1) {
println(numbers[index])
}
Output:
3
6
9
12
Accessing elements using the index in reverse
If we wanted to access element of the list in reverse order, we would do the following in Java:
List<Integer> numbers = new ArrayList(){{
add(3);
add(6);
add(9);
add(12);
}};for(int index=numbers.size()-1; index>=0; index--) {
System.out.println(numbers.get(index));
}
In Kotlin:
val numbers = listOf(3, 6, 9, 12)for(index in numbers.size-1 downTo 0) {
println(numbers[index])
}
Output:
12
9
6
3
Accessing elements using the index with custom increment
And finally if we are looking for a non-1 increment or decrement (using increments of 2 as an example here):
Java version:
List<Integer> numbers = new ArrayList(){{
add(3);
add(6);
add(9);
add(12);
}};for(int index=0; index<numbers.size(); index=index+2) {
System.out.println(numbers.get(index));
}
Kotlin version:
val numbers = listOf(3, 6, 9, 12)for(index in 0..numbers.size-1 step 2) {
println(numbers[index])
}
Output:
3
9
And that is a wrap! I hope this helps with being able to fluently switch between writing for loops in Java and Kotlin!