Add sample for filter

This commit is contained in:
Brian Plummer
2020-02-22 12:15:38 -05:00
committed by Ilya Gorbunov
parent 840f222867
commit f887a29279
5 changed files with 16 additions and 0 deletions
@@ -3590,6 +3590,8 @@ public inline fun CharArray.dropWhile(predicate: (Char) -> Boolean): List<Char>
/**
* Returns a list containing only elements matching the given [predicate].
*
* @sample samples.collections.Collections.Filtering.filter
*/
public inline fun <T> Array<out T>.filter(predicate: (T) -> Boolean): List<T> {
return filterTo(ArrayList<T>(), predicate)
@@ -699,6 +699,8 @@ public inline fun <T> Iterable<T>.dropWhile(predicate: (T) -> Boolean): List<T>
/**
* Returns a list containing only elements matching the given [predicate].
*
* @sample samples.collections.Collections.Filtering.filter
*/
public inline fun <T> Iterable<T>.filter(predicate: (T) -> Boolean): List<T> {
return filterTo(ArrayList<T>(), predicate)
@@ -375,6 +375,8 @@ public fun <T> Sequence<T>.dropWhile(predicate: (T) -> Boolean): Sequence<T> {
* Returns a sequence containing only elements matching the given [predicate].
*
* The operation is _intermediate_ and _stateless_.
*
* @sample samples.collections.Collections.Filtering.filter
*/
public fun <T> Sequence<T>.filter(predicate: (T) -> Boolean): Sequence<T> {
return FilteringSequence(this, true, predicate)
@@ -803,6 +803,15 @@ class Collections {
}
class Filtering {
@Sample
fun filter() {
val numbers: List<Int> = listOf(1, 2, 3, 4)
val evenNumbers = numbers.filter { number -> number.rem(2) == 0 }
assertPrints(evenNumbers, "[2, 4]")
}
@Sample
fun filterNotNull() {
val numbers: List<Int?> = listOf(1, 2, null, 4)
@@ -548,6 +548,7 @@ object Filtering : TemplateGroupBase() {
specialFor(ArraysOfUnsigned) { inlineOnly() }
doc { "Returns a ${f.mapResult} containing only ${f.element.pluralize()} matching the given [predicate]." }
sample("samples.collections.Collections.Filtering.filter")
returns("List<T>")
body {
"""