Skip to content

Instantly share code, notes, and snippets.

@fdoyle
Created November 13, 2015 20:50
Show Gist options
  • Save fdoyle/268718acbd060e799cbb to your computer and use it in GitHub Desktop.
Save fdoyle/268718acbd060e799cbb to your computer and use it in GitHub Desktop.
made these as an exercise, then found out they were in sequence. oh well.
package com.lacronicus.kotlinlistmethods
import java.util.ArrayList
/**
* Created by fdoyle on 11/13/15.
*/
fun <T, R> List<T>.map(mapFunc: (T) -> R) : List<R> {
val rs = ArrayList<R>(this.size())
for (value in this) {
rs.add(mapFunc.invoke(value))
}
return rs
}
fun <T> List<T>.filter(filterFunc: (T) -> Boolean) : List<T> {
val ts = ArrayList<T>()
for (value in this) {
if (filterFunc.invoke(value))
ts.add(value)
}
return ts
}
fun <T, R> List<T>.flatMap(mapFunc: (T) -> List<R>) : List<R> {
val rs = ArrayList<R>()
for (value in this) {
val newValueList = mapFunc.invoke(value)
for(newValue in newValueList)
rs.add(newValue)
}
return rs
}
fun <T> List<T>.doOnEach(doOnEach: (T) -> Unit){
for (value in this) {
doOnEach.invoke(value);
}
}
@fdoyle
Copy link
Author

fdoyle commented Nov 13, 2015

Like i said, probably best to use Sequence, but for something quick and dirty, this'll do the job.

For reference, you can do:

myList.iterator().toSequence().map/filter/whatever

or something like that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment