• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

ivan-moto/30-seconds-of-kotlin: Kotlin snippets that you can understand quickly, ...

原作者: [db:作者] 来自: 网络 收藏 邀请

开源软件名称(OpenSource Name):

ivan-moto/30-seconds-of-kotlin

开源软件地址(OpenSource Url):

https://github.com/ivan-moto/30-seconds-of-kotlin

开源编程语言(OpenSource Language):

Kotlin 100.0%

开源软件介绍(OpenSource Introduction):

Support this and other projects from Ivan Mwiruki here.


Kotlin

30 seconds of Kotlin

Curated collection of useful Kotlin 1.3 snippets that you can understand quickly, using only stdlib functionality.

Snippets are optimized for readability and comprehension, sometimes at the expense of performance.

Note: This project is inspired by, but in no way affiliated with, 30 Seconds of Code.

Table of Contents

List

Functions operating on the most fundamental data structure: List.

View contents

Function

Kotlin's first class functions make it easy to manipulate functions.

View contents

Lazy

Functions operating on Kotlin's built in Lazy type.

View contents

Map

Functions operating on Maps.

View contents

Related projects


List

all

Returns true if the provided predicate function returns true for all elements in a list, false otherwise.

fun <T> all(list: List<T>, predicate: (T) -> Boolean): Boolean =
    list.all(predicate)

allEqual

Checks if all elements in a list are equal.

fun <T> allEqual(list: List<T>): Boolean =
    if (list.isEmpty()) false else list.all { it == list[0] }

any

Returns true if the provided predicate function returns true for at least one element in a list, false otherwise.

fun <T> any(list: List<T>, predicate: (T) -> Boolean): Boolean =
    list.any(predicate)

bifurcate

Splits list into two groups. For every element in a list, if the corresponding boolean in another list is true, add the element to the first group; otherwise, add it to the second group.

// For example:
bifurcate(listOf("beep", "boop", "foo", "bar"), listOf(true, true, false, true)) // [[beep, boop, bar], [foo]]
fun <T> bifurcate(list: List<T>, filter: List<Boolean>): Pair<List<T>, List<T>> {
    require(list.size == filter.size)
    return list.zip(filter).partition { it.second }
        .let { (list1, list2) -> list1.map { it.first } to list2.map { it.first } }
}

bifurcateBy

Splits values into two groups according to a predicate function, which specifies which group an element in the input list belongs to. If the predicate function returns true, the list element belongs to the first group; otherwise, it belongs to the second group.

fun <T> bifurcateBy(list: List<T>, predicate: (T) -> Boolean): Pair<List<T>, List<T>> =
    list.partition(predicate)

chunk

Chunks a list into smaller lists of a specified size. The last list in the resulting list may have less elements than the given size.

// For example:
chunk(listOf(1, 2, 3, 4, 5), 2) // [[1 ,2], [3, 4], [5]]
fun <T> chunk(list: List<T>, size: Int): List<List<T>> =
    list.chunked(size)

compact

Removes "falsey" values from a list.

Kotlin doesn't distinguish falsey values but they are (false, null, 0, "", [], and NaN).

fun <T> compact(list: List<T?>): List<T> {
    fun isTruthy(t: T?): Boolean = when(t) {
        null -> false
        is Boolean -> t
        is Double -> t != Double.NaN
        is Number -> t.toInt() != 0
        is String -> !t.isEmpty()
        is Array<*> -> t.size != 0
        is Collection<*> -> !t.isEmpty()
        else -> true
    }
    @Suppress("UNCHECKED_CAST")
    return list.filter(::isTruthy) as List<T>
}

countBy

Groups the elements of a list based on the given function and returns the count of elements in each group.

// For example:
countBy(listOf(6.1, 4.2, 6.3)) { floor(it) } // {4.0: 1, 6.0: 2}
countBy(listOf("one", "two", "three")) { it.length } // {3: 2, 5: 1}
fun <T, K> countBy(list: List<T>, function: (T) -> K): Map<K, Int> =
    list.groupingBy(function).eachCount()

countOccurrences

Counts the occurrences of a value in a list, using a provided equality function.

fun <T> countOccurrences(list: List<T>, target: T, equals: (T, T) -> Boolean = Objects::equals): Int =
    list.count { equals(target, it) }

concat

Concatenates multiple lists into a single list, preserving the order of the passed in elements.

fun <T> concat(first: List<T>, vararg others: List<T>): List<T> =
    first.asSequence().plus(others.asSequence().flatten()).toList()

corresponds

Tests whether every element of the first list relates to the corresponding element in the second list by satisfying the given predicate.

// For example:
corresponds(listOf(1, 2, 3), listOf(2, 3, 4)) { i1, i2 -> i1 == i2 - 1 } // true
fun <T, U> corresponds(first: List<T>, second: List<U>, predicate: (T, U) -> Boolean): Boolean =
    (first.size == second.size) && (first.zip(second).all { (t, u) -> predicate(t, u) })

crossProduct

Creates a cross product: forming a pair from each value in the first list to each value in the second list.

// For example:
crossProduct(listOf(1, 2), listOf('a', 'b')) // [[1, 'a'], [1, 'b'], [2, 'a'], [2, 'b']]
fun <T, U> crossProduct(first: List<T>, second: List<U>): List<Pair<T, U>> =
    first.flatMap { a -> second.map { b -> a to b } }

cycle

Produces a Sequence which cycles indefinitely through the given list.

// For example:
cycle(listOf(1, 2, 3)) // 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3...
fun <T> cycle(list: List<T>): Sequence<T> = 
    generateSequence(if (list.isNotEmpty()) 0 else null) { (it + 1) % list.size }
        .map { list[it] }

difference

Returns a list of elements contained in the first list that are not present in the second list.

// For example:
difference(listOf(1, 2, 3), listOf(1, 2, 4)) // [3]
fun <T> difference(first: List<T>, second: List<T>): List<T> =
    (first subtract second).toList()

differenceBy

Returns a list of elements contained in the first list that are not present in the second list, after applying the provided function to each list element of both.

fun <T, R> differenceBy(first: List<T>, second: List<T>, function: (T) -> R): List<T> =
    with(second.toSet().map(function)) {
        first.filterNot { contains(function(it)) }
    }

differenceWith

Filters out all elements from the first list for which the comparator function does not return true for that element and every element in the second list.

fun <T> differenceWith(first: List<T>, second: List<T>, function: (T, T) -> Boolean): List<T> =
    first.filter { a -> second.none { b -> function(a, b) } }

distinct

Returns all distinct elements.

fun <T> distinct(list: List<T>): List<T> =
    list.distinct()

drop

Returns a new list with n elements removed from the left.

fun <T> drop(list: List<T>, n: Int): List<T> =
    list.drop(n)

dropRight

Returns a new list with n elements removed from the right.

fun <T> dropRight(list: List<T>, n: Int): List<T> =
    list.dropLast(n)

dropRightWhile

Removes elements from the end of a list until the passed function returns true. Returns the remaining elements in the list.

fun <T> dropRightWhile(list: List<T>, predicate: (T) -> Boolean): List<T> =
    list.dropLastWhile(predicate)

dropWhile

Removes elements from the beginning of a list until the passed function returns true. Returns the remaining elements in the list.

fun <T> dropWhile(list: List<T>, predicate: (T) -> Boolean): List<T> =
    list.dropWhile(predicate)

endsWith

Checks whether the given list ends with the given sublist.

fun <T> endsWith(list: List<T>, subList: List<T>): Boolean =
    list.takeLast(subList.size) == subList

everyNth

Returns every nth element in a list.

// For example:
everyNth(listOf(1, 2, 3, 4, 5, 6), 2) // [ 2, 4, 6 ]
fun <T> everyNth(list: List<T>, nth: Int): List<T> =
    list.windowed(nth, nth, partialWindows = false).map { it.last() }

existsUnique

Checks if a unique element exists such that the predicate holds.

// For example:
existsUnique(listOf(1, 2, 3, 4, 5, 3)) { it == 3 } // false
fun <T> existsUnique(list: List<T>, predicate: (T) -> Boolean): Boolean {
    var exists = false
    for (t in list) {
        if (predicate(t)) {
            if (exists) {
                return false
            } else {
                exists = true
            }
        }
    }
    return exists
}

filterNonUnique

Filters out the non-unique values in a list.

fun <T> filterNonUnique(list: List<T>): List<T> =
    list.distinct()

热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap