├── .gitignore ├── LICENSE ├── README.md ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src └── test └── kotlin └── com └── winterbe └── kotlin └── sequences ├── AdvancedExamples.kt ├── BasicExamples.kt ├── ExtendingSequences.kt ├── PerformanceTest.kt ├── ProcessingOrder.kt └── ReusingSequences.kt /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | .gradle 3 | .idea 4 | out 5 | *.iml -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2018 Benjamin Winterberg 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Kotlin Examples 2 | 3 | This repo contains the example code snippets used in my Kotlin-related blog posts on [winterbe.com](https://winterbe.com): 4 | 5 | - [Kotlin Sequence Tutorial](https://winterbe.com/posts/2018/07/23/kotlin-sequence-tutorial/) 6 | 7 | # License 8 | 9 | MIT 10 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'org.jetbrains.kotlin.jvm' version '1.2.51' 3 | } 4 | 5 | group 'com.winterbe' 6 | version '1.0-SNAPSHOT' 7 | 8 | repositories { 9 | mavenCentral() 10 | } 11 | 12 | dependencies { 13 | compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8" 14 | testCompile 'junit:junit:4.11' 15 | testCompile "org.jetbrains.kotlin:kotlin-test-junit" 16 | } 17 | 18 | compileKotlin { 19 | kotlinOptions.jvmTarget = "1.8" 20 | } 21 | compileTestKotlin { 22 | kotlinOptions.jvmTarget = "1.8" 23 | } -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/winterbe/kotlin-examples/69a232febc1bddca0454e21cae5303f896b3a41d/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.8-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'kotlin-examples' 2 | 3 | -------------------------------------------------------------------------------- /src/test/kotlin/com/winterbe/kotlin/sequences/AdvancedExamples.kt: -------------------------------------------------------------------------------- 1 | package com.winterbe.kotlin.sequences 2 | 3 | import org.junit.Test 4 | 5 | class AdvancedExamples { 6 | 7 | data class Person(val name: String, val age: Int) 8 | 9 | private val persons = listOf( 10 | Person("Peter", 16), 11 | Person("Anna", 28), 12 | Person("Anna", 23), 13 | Person("Sonya", 39) 14 | ) 15 | 16 | @Test 17 | fun `reduce sequence of numbers into digit sum`() { 18 | val result = sequenceOf(1, 2, 3, 4, 5) 19 | .asSequence() 20 | .reduce { acc, num -> 21 | acc + num 22 | } 23 | 24 | print(result) // 15 25 | } 26 | 27 | @Test 28 | fun flatMap() { 29 | val result = sequenceOf(listOf(1, 2, 3), listOf(4, 5, 6)) 30 | .flatMap { 31 | it.asSequence().filter { it % 2 == 1 } 32 | } 33 | .toList() 34 | 35 | print(result) // [1, 3, 5] 36 | } 37 | 38 | @Test 39 | fun `flatten elements`() { 40 | val result = sequenceOf(listOf(1, 2, 3), listOf(4, 5, 6)) 41 | .flatten() 42 | .toList() 43 | 44 | print(result) // [1, 2, 3, 4, 5, 6] 45 | } 46 | 47 | @Test 48 | fun `associate by a given property`() { 49 | val result = persons 50 | .asSequence() 51 | .associateBy { it.name } 52 | 53 | print(result) // {Peter=Person(name=Peter, age=16), Anna=Person(name=Anna, age=23), Sonya=Person(name=Sonya, age=39)} 54 | } 55 | 56 | @Test 57 | fun `group by a given property`() { 58 | val result = persons 59 | .asSequence() 60 | .groupBy { it.name } 61 | 62 | print(result) // {Peter=[Person(name=Peter, age=16)], Anna=[Person(name=Anna, age=28), Person(name=Anna, age=23)], Sonya=[Person(name=Sonya, age=39)]} 63 | } 64 | 65 | @Test 66 | fun `any matches predicate`() { 67 | val result = sequenceOf(1, 2, 3, 4, 5) 68 | .filter { it % 2 == 1 } 69 | .any { it % 2 == 0 } 70 | 71 | print(result) // false 72 | } 73 | 74 | @Test 75 | fun `map sequences`() { 76 | val map = mapOf( 77 | "a" to 10, 78 | "b" to 20, 79 | "c" to 30 80 | ) 81 | 82 | val result = map 83 | .asSequence() 84 | .filter { it.value < 20 } 85 | .map { it.key } 86 | .single() 87 | 88 | print(result) // a 89 | } 90 | 91 | @Test 92 | fun `sort by property`() { 93 | val result = persons 94 | .asSequence() 95 | .sortedBy { it.age } 96 | .toList() 97 | 98 | print(result) // [Person(name=Peter, age=16), Person(name=Anna, age=23), Person(name=Anna, age=28), Person(name=Sonya, age=39)] 99 | } 100 | 101 | @Test 102 | fun `distinct by property`() { 103 | val result = persons 104 | .asSequence() 105 | .distinctBy { it.name } 106 | .toList() 107 | 108 | print(result) // [Person(name=Peter, age=16), Person(name=Anna, age=28), Person(name=Sonya, age=39)] 109 | } 110 | 111 | @Test 112 | fun `max by property`() { 113 | val result = persons 114 | .asSequence() 115 | .maxBy { it.age } 116 | 117 | print(result) // Person(name=Sonya, age=39) 118 | } 119 | 120 | @Test 121 | fun `operate on element indices`() { 122 | val result = sequenceOf("a", "b", "c", "d") 123 | .withIndex() 124 | .filter { it.index % 2 == 0 } 125 | .map { it.value } 126 | .toList() 127 | 128 | print(result) // [a, c] 129 | } 130 | 131 | @Test 132 | fun `add and remove elements from sequence`() { 133 | val result = sequenceOf("a", "b", "c") 134 | .plus("d") 135 | .minus("c") 136 | .map { it.toUpperCase() } 137 | .toList() 138 | 139 | print(result) // [A, B, D] 140 | } 141 | 142 | } -------------------------------------------------------------------------------- /src/test/kotlin/com/winterbe/kotlin/sequences/BasicExamples.kt: -------------------------------------------------------------------------------- 1 | package com.winterbe.kotlin.sequences 2 | 3 | import org.junit.Test 4 | 5 | class BasicExamples { 6 | 7 | @Test 8 | fun `basic introduction example`() { 9 | data class Person(val name: String, val age: Int) 10 | 11 | val persons = listOf( 12 | Person("Peter", 16), 13 | Person("Anna", 23), 14 | Person("Anna", 28), 15 | Person("Sonya", 39) 16 | ) 17 | 18 | val names = persons 19 | .asSequence() 20 | .filter { it.age > 18 } 21 | .map { it.name } 22 | .distinct() 23 | .sorted() 24 | .toList() 25 | 26 | print(names) // [Anna, Sonya] 27 | } 28 | 29 | @Test 30 | fun `create sequence without input collection`() { 31 | val result = sequenceOf(1, 2, 3, 4, 5) 32 | .filter { it % 2 == 1 } 33 | .toList() 34 | 35 | print(result) // [1, 3, 5] 36 | } 37 | 38 | @Test 39 | fun `generate sequence from function`() { 40 | val result = generateSequence(0) { it + 1 } 41 | .take(5) 42 | .filter { it % 2 == 1 } 43 | .toList() 44 | 45 | print(result) // [1, 3, 5] 46 | } 47 | 48 | @Test 49 | fun `create sequence from a range of numbers`() { 50 | val result = (1..6) 51 | .asSequence() 52 | .filter { it % 2 == 1 } 53 | .toList() 54 | 55 | print(result) // [1, 3, 5] 56 | } 57 | 58 | } -------------------------------------------------------------------------------- /src/test/kotlin/com/winterbe/kotlin/sequences/ExtendingSequences.kt: -------------------------------------------------------------------------------- 1 | package com.winterbe.kotlin.sequences 2 | 3 | import org.junit.Test 4 | 5 | class ExtendingSequences { 6 | 7 | private fun Sequence.shuffle(): Sequence { 8 | return toMutableList() 9 | .apply { shuffle() } 10 | .asSequence() 11 | } 12 | 13 | @Test 14 | fun `writing your own sequence operations`() { 15 | val result = sequenceOf(1, 2, 3, 4, 5) 16 | .shuffle() 17 | .toList() 18 | 19 | print(result) 20 | } 21 | 22 | } -------------------------------------------------------------------------------- /src/test/kotlin/com/winterbe/kotlin/sequences/PerformanceTest.kt: -------------------------------------------------------------------------------- 1 | package com.winterbe.kotlin.sequences 2 | 3 | import org.junit.Test 4 | import java.util.concurrent.TimeUnit 5 | import kotlin.system.measureNanoTime 6 | 7 | class PerformanceTest { 8 | 9 | @Test 10 | fun testPerf1() { 11 | val sequence = generateSequence(1) { it + 1 }.take(50_000_000) 12 | val list = sequence.toList() 13 | measure("list - filter - average") { 14 | list.filter { it % 3 == 0 }.average() 15 | } 16 | // 8644 ms 17 | } 18 | 19 | @Test 20 | fun testPerf2() { 21 | val sequence = generateSequence(1) { it + 1 }.take(50_000_000) 22 | val list = sequence.toList() 23 | measure("list - filter - sum") { 24 | list.filter { it % 3 == 0 }.sum() 25 | } 26 | // 11127 ms 27 | } 28 | 29 | @Test 30 | fun testPerf3() { 31 | val sequence = generateSequence(1) { it + 1 }.take(50_000_000) 32 | measure("sequence - filter - average") { 33 | sequence.filter { it % 3 == 0 }.average() 34 | } 35 | // 822 ms 36 | } 37 | 38 | @Test 39 | fun testPerf4() { 40 | val sequence = generateSequence(1) { it + 1 }.take(50_000_000) 41 | measure("sequence - filter - sum") { 42 | sequence.filter { it % 3 == 0 }.sum() 43 | } 44 | // 784 ms 45 | } 46 | 47 | private fun measure(name: String, block: () -> Unit) { 48 | val nanoTime = measureNanoTime(block) 49 | val millis = TimeUnit.NANOSECONDS.toMillis(nanoTime) 50 | println("$name: $millis ms") 51 | } 52 | } -------------------------------------------------------------------------------- /src/test/kotlin/com/winterbe/kotlin/sequences/ProcessingOrder.kt: -------------------------------------------------------------------------------- 1 | package com.winterbe.kotlin.sequences 2 | 3 | import org.junit.Test 4 | 5 | class ProcessingOrder { 6 | 7 | @Test 8 | fun `missing terminal operator prints nothing`() { 9 | sequenceOf("A", "B", "C") 10 | .filter { 11 | println("filter: $it") 12 | true 13 | } 14 | } 15 | 16 | @Test 17 | fun `elements are processed vertically one by one`() { 18 | sequenceOf("A", "B", "C") 19 | .filter { 20 | println("filter: $it") 21 | true 22 | } 23 | .forEach { 24 | println("forEach: $it") 25 | } 26 | // filter: A 27 | // forEach: A 28 | // filter: B 29 | // forEach: B 30 | // filter: C 31 | // forEach: C 32 | } 33 | 34 | @Test 35 | fun `early exit`() { 36 | val result = sequenceOf("A", "B", "C") 37 | .map { 38 | println("map: $it") 39 | it.toUpperCase() 40 | } 41 | .any { 42 | println("any: $it") 43 | it.startsWith("B") 44 | } 45 | 46 | println(result) 47 | 48 | // map: A 49 | // any: A 50 | // map: B 51 | // any: B 52 | // true 53 | } 54 | 55 | @Test 56 | fun `unoptimized order`() { 57 | sequenceOf("a", "b", "c", "d") 58 | .map { 59 | println("map: $it") 60 | it.toUpperCase() 61 | } 62 | .filter { 63 | println("filter: $it") 64 | it.startsWith("a", ignoreCase = true) 65 | } 66 | .forEach { 67 | println("forEach: $it") 68 | } 69 | 70 | // map: a 71 | // filter: A 72 | // forEach: A 73 | // map: b 74 | // filter: B 75 | // map: c 76 | // filter: C 77 | // map: d 78 | // filter: D 79 | } 80 | 81 | @Test 82 | fun `optimized order`() { 83 | sequenceOf("a", "b", "c", "d") 84 | .filter { 85 | println("filter: $it") 86 | it.startsWith("a", ignoreCase = true) 87 | } 88 | .map { 89 | println("map: $it") 90 | it.toUpperCase() 91 | } 92 | .forEach { 93 | println("forEach: $it") 94 | } 95 | 96 | // filter: a 97 | // map: a 98 | // forEach: A 99 | // filter: b 100 | // filter: c 101 | // filter: d 102 | } 103 | 104 | } -------------------------------------------------------------------------------- /src/test/kotlin/com/winterbe/kotlin/sequences/ReusingSequences.kt: -------------------------------------------------------------------------------- 1 | package com.winterbe.kotlin.sequences 2 | 3 | import org.junit.Test 4 | 5 | class ReusingSequences { 6 | 7 | @Test 8 | fun `reusing sequences`() { 9 | val sequence = sequenceOf(1, 2, 3, 4, 5) 10 | .filter { it % 2 == 1 } 11 | println(sequence.toList()) // [1, 3, 5] 12 | println(sequence.first()) // 1 13 | } 14 | } --------------------------------------------------------------------------------