Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Expressive & Efficient Collection Processing in Kotlin

Expressive & Efficient Collection Processing in Kotlin

This Presentation covers Kotlin Collections Examples and Samples of how to do aggregating, transformation, searching, filtering and checks and actions on Kotlin Collections

Presented on September 14th,2019 at Kotlin Everywhere Nairobi Episode 03

Harun Wangereka

September 14, 2019
Tweet

More Decks by Harun Wangereka

Other Decks in Programming

Transcript

  1. Iterator object knows how to iterate over a collection public

    interface Iterator<out T> { public operator fun next(): T public operator fun hasNext(): Boolean }
  2. Next on hierarchy is Collection public interface Collection<out E> :

    Iterable<E> { public val size: Int public fun isEmpty(): Boolean public operator fun contains(element: @UnsafeVariance E): Boolean override fun iterator(): Iterator<E> public fun containsAll(elements: Collection<@UnsafeVariance E>): Boolean }
  3. Summary • Create - We have mutable and read-only •

    Operators - Functional operations plus,minus, plus assign and minus assign • Transformers - build new collections based on conditions provided • Aggregators - operations that return single value based on collection content • Searching - getting particular elements • Filtering - filter-in with some predicate/condition • Actions - [action] on a particular iterable
  4. • Retrieving Collections Parts - Retrieves parts of collections -

    • Retrieving Single Elements • Collection Ordering • Collections write operations - add(),remove() • List/Set/Map Specific Operations
  5. ..the old way var count = 0 var total =

    0.0 for (album in albumList){ if (album.genre == "HipHop"){ count ++ total += album.averageRating } } val average = total/ count average.print()
  6. The collections.way val avg = albumList.filter { it.genre == "HipHop"

    } .map { it.averageRating } .average() .print()
  7. ..the old way val speakersList :List<SpeakersModel> = getSpeakersInfo() val sessionList

    : List<SessionsModel> = snapshots.toObjects<SessionsModel>() sessionList.map { sessionModel -> val sessionSpeakerIdList = sessionModel.speaker_id sessionSpeakerIdList.forEach { speakerId -> speakersList.forEach {speakerModel -> if (sessionSpeakerIdList.contains(speakerModel.id)){ sessionModel.speakerList.add(speakerModel) } } } }
  8. The collections.way val speakerById : Map<Int, SpeakersModel> = getSpeakerInfo().associateBy {

    it.id} val sessionList : List<SessionsModel> = snapshots.toObjects() sessionList.onEach { sessionsModel -> sessionsModel.speaker_id.mapNotNull { speakerById[it]?.let { speakerModel -> sessionsModel.speakerList.add(speakerModel) } } }