Iterable и Collection

List и Set

Map

Интерфейс Iterable

public interface List<out E> : Collection<E>
public interface Collection<out E> : Iterable<E>
public interface Iterable<out T> {
    /**
     * Returns an iterator over the elements of this object.
     */
    public operator fun iterator(): Iterator<T>
}

Интерфейс Iterator

public interface Iterator<out T> {
    /**
     * Returns the next element in the iteration.
     */
    public operator fun next(): T

    /**
     * Returns "true" if the iteration has more elements.
     */
    public operator fun hasNext(): Boolean
}

Пример итератора

fun <T> Iterator<T>.str(): String {
    var out = "["
    while (hasNext())
        out += next().toString() + "; "
    return out.dropLast(2) + "]"
}
...
println(students.iterator().str())

[Sheldon; Leonard; Howard; Raj; Penny; Amy; Bernadette]

Вложенный итератор

val math = Course("Math",
    listOf(0, 1, 2).map { students[it] } )
val phys = Course("Phys",
    listOf(0, 1, 3).map { students[it] } )
val chem = Course("Chem",
    listOf(0, 5).map { students[it] } )
val courses = listOf(math, phys, chem)

val studyingStudent = ???

flatMap

public inline fun <T, R, C : MutableCollection<in R>> 
    Iterable<T>.flatMapTo(
        destination: C, 
        transform: (T) -> Iterable<R>
    ): C {
        for (element in this) {
            val list = transform(element)
            destination.addAll(list)
        }
        return destination
    }

flatMap

val studyingStudent = courses.flatMap { it.students }

[Sheldon, Leonard, Howard, Sheldon, Leonard, Raj, Sheldon, Amy]

Sequences

public interface Sequence<out T> {
    public operator fun iterator(): Iterator<T>
}
val numbersSequence = sequenceOf("four", "three", "two", "one")

val numbers = listOf("one", "two", "three", "four")
val numbersSequence = numbers.asSequence()

Работа последовательностей