Kotlinlearncs.online LogoJava

    ← Prev

    Index

    Next →

    Kotlin
    Java
    • Graphs : 59

    • map-reduce-filter : 58

    • Generics : 57

    • Implementing a Map : 56

    • Hashing : 55

    • Binary Search : 54

    • Quicksort : 53

    • Merge Sort : 52

    • Sorting Algorithms : 51

    • Practice with Recursion : 50

    • Trees and Recursion : 49

    • Trees : 48

    • Recursion : 47

    • Lists Review and Performance : 46

    • Linked Lists : 45

    • Algorithms and Lists : 44

    • Lambda Expressions : 43

    • Anonymous Classes : 42

    • Practice with Interfaces : 41

    • Implementing Interfaces : 40

    • Using Interfaces : 39

    • Working with Exceptions : 38

    • Throwing Exceptions : 37

    • Catching Exceptions : 36

    • References and Polymorphism : 35

    • References : 34

    • Data Modeling 2 : 33

    • Equality and Object Copying : 32

    • Polymorphism : 31

    • Inheritance : 30

    • Data Modeling 1 : 29

    • Companion Objects : 28

    • Encapsulation : 27

    • Constructors : 26

    • Objects, Continued : 25

    • Introduction to Objects : 24

    • Compilation and Immutability : 23

    • Practice with Collections : 22

    • Maps and Sets : 21

    • Lists and Type Parameters : 20

    • Imports and Libraries : 19

    • Multidimensional Arrays : 18

    • Practice with Strings : 17

    • null : 16

    • Algorithms and Strings : 15

    • Strings : 14

    • Functions and Algorithms : 13

    • Practice with Functions : 12

    • More About Functions : 11

    • Errors and Debugging : 10

    • Functions : 9

    • Practice with Loops and Algorithms : 8

    • Algorithms I : 7

    • Loops : 6

    • Arrays : 5

    • Compound Conditionals : 4

    • Conditional Expressions and Statements : 3

    • Operations on Variables : 2

    • Variables and Types : 1

    • Hello, world! : 0

    map-reduce-filter

    class Dog(val name: String)
    listOf(Dog("Shadow"), Dog("Chuchu"), Dog("Lulu"))
    .map { it.name }
    .sorted()
    .forEach { println(it) }

    This lesson introduces a new programming paradigm that is particular useful for working with data: map-reduce-filter. We’ll manipulated linear collections of data using good old for loops. But we can do better. Let’s see how!

    Iterative Building Blocks
    Iterative Building Blocks

    Many of the code and algorithms we’ve written together have operated on sequential data, stored in either arrays or Lists. And we’ve seen and identified common patterns for working with this kind of data. Such as counting:

    val values = listOf(1, 2, 4)
    var count = 0
    for (value in values) {
    if (value > 1) {
    count++
    }
    }
    println(count)

    And searching:

    val values = listOf(1, 2, 4)
    var found = false
    for (value in values) {
    if (value == 2) {
    found = true
    break
    }
    }
    println(found)

    And transforming:

    val values = listOf(1, 2, 4)
    val strings = mutableListOf<String>()
    for (value in values) {
    strings += value.toString() + "ee"
    }
    println(strings)

    And filtering:

    val values = listOf(1, 2, 4)
    val evens = mutableListOf<Int>()
    for (value in values) {
    if (value % 2 == 0) {
    evens += value
    }
    }
    println(evens)

    And combining:

    val values = listOf(1, 2, 4)
    var combined = ""
    for (value in values) {
    combined += value.toString()
    }
    println(combined)

    And while these are fine building blocks for creating larger programs, there is something a bit repetitive and dull about them. Every one has the same overall structure: the same loop, many have an if statement, etc. Shouldn’t there be a better, more compact way of expressing these kind of patterns?

    map-reduce-filter
    map-reduce-filter

    Yes. There is. In Kotlin we refer to this as map-reduce-filter, which is also sometimes known as stream data processing.

    map-reduce-filter allows us to work with sequential data by composing powerful programming primitives to great effect. These methods are built right in to all of the Kotlin collections—arrays, lists, and maps—that we’ve already been working with!

    Let’s examine how to utilize common stream operations to replace the repetitive loop-based code we wrote above. First, let’s look at one of the most basic collection operations—map:

    // Collection map

    We can also filter streams using… filter. Let’s see how:

    // filter

    And, we can even reduce a Stream until a single value with reduce, a surprisingly powerful primitive.

    // reduce

    Why map-reduce-filter?
    Why map-reduce-filter?

    This programming pattern may seem alien to you at first. That’s not surprising. A famous silicon valley tech thought leader has pointed out that powerful programming ideas usually feel strange and even bizarre at first. But, as you come to appreciate them, not only do they become more natural, but the older less-powerful ways of doing things start to see even more limited.

    Compared to for loops, map-reduce-filter pipelines are:

    map-reduce-filter Example
    map-reduce-filter Example

    To wrap up, let’s have some fun working with one of our favorite data sets:

    class Dog(val name: String, val age: Int)

    Homework: Escape a Maze

    Created By: Geoffrey Challen
    / Version: 2021.4.0

    Let's get some more practice with algorithms by escaping from a maze! Implement a method named escape that accepts a single parameter, a Maze object with methods explained below. Your goal is to manipulate the maze until you reach the exit, and then return the maze when you are finished.

    To navigate the maze, using the following Maze methods:

    • isFinished(): returns true when you have reached the exit of the maze
    • turnRight() rotates your character 90 degrees to the right
    • turnLeft() rotates your character 90 degrees to the left
    • canMove() returns true if you can move one cell forward, false otherwise. Your path may be blocked by a wall!
    • move() moves your character one cell forward and increases the step counter

    The passed Maze object represents a simply-connected or perfect maze: one that contains no loops. As a result, we suggest that you pursue a classic maze escape algorithm: wall following. Simply put, in a maze that contains no loops, as long as you continue following a wall you will eventually reach the exit. In a corn maze, you might implement this by simply maintaining contact with a wall (right or left) until you complete the maze. However, you'll need to think a bit about how to implement this algorithm to finish this problem.

    More Practice

    Need more practice? Head over to the practice page.