How many collections are created while running the code below in kotlin?

Viewed 83

All the extension functions for collections that allow us to work with collections in a functional style are defined as inline functions. That means their bodies are generated in the byte code instead of function calls. Another thing that we can notice looking at declarations is that these functions return new collections. For instance, a filter creates a new collection that contains the result and returns it. how do I calculate how many collections are created? Example: How many collections are created while running the code below?

val list = listOf(1, 2, 3)
val maxOddSquare = list
     .map{it * it}
     .filter{it % 2 == 1}
     .max() 
2 Answers

Three. Let's count all the intermediate collections. At first, we create an initial list that contains all the elements. Then when we call map, the map creates a new collection and returns it as a result. Then we call filter, filter on its turn again creates a new collection and returns it. At last, we call max which just returns the value, which makes it three as the answer. When you use simple operations on collections, all the intermediate collections are created.

val list = listOf(1, 2, 3) // [1, 2, 3]
val maxOddSquare = list
     .map{it * it}         // [1, 4, 9]
     .filter{it % 2 == 1}  // [1, 9]
     .max() 

As Anvar already answered correctly, three collections are created. It has nothing to do with inlining the code. That just saves the method calls but the collections are created anyways. Creating the collections also doesn't mean that the contained objects are duplicated. All three collections point to the same objects, so this might not be as expensive as you think.

If you want the same behaviour as in Java Streams, you would use a sequence in Kotlin, which provides all the same methods (retuning a sequence, not a collection):

val list = listOf(1, 2, 3)
val maxOddSquare = list
    .asSequence()
    .map { it * it }
    .filter { it % 2 == 1 }
    .max()

PS: max() is deprecated, you should use maxOrNull() instead.

Related