当前位置:网站首页>Quickly master kotlin set functions
Quickly master kotlin set functions
2022-07-28 16:45:00 【AndroidKt】
original text :https://medium.com/mobile-app-development-publication/kotlin-collection-functions-cheat-sheet-975371a96c4b
author :Elye
Preface
Do you know Kotlin Collection How many operation functions are there ?200 Multiple . It may take some time to browse through the function names alphabetically , Not to mention quickly finding functions that meet your business scenarios , Even some functions you may not know its existence , This situation is very distressing ! Fortunately, I recently read about Kotlin Collection operation function article , According to the function , Divide it into 5 class :Creation、Convert、Change、Choose and Conclude, For each major category, the author further divides into subcategories , All types are named with C Begin with Collection aggregate , Such feelings ! Through the quick search memo formed by classification, all functions are presented in a tree structure in front of you , It's easier to find . For some functions that are not easy to understand , Some illustrations are also provided in the article to help explain , For some common functions , The author also added links to official documents for us to understand . Thanks for the author's arrangement , Let's start with the text .
classification
It is mainly divided into 5 Species category :
Creation: New collection , for example
listOfConvert: Convert sets , for example
asMapChange: Change set , for example
mapChoose: Access the collection , for example
getConclude: Summary Set , for example
sum

How to quickly find
Scene one :
Suppose you want to find a function that multiplies the values of all integer items in the list , Considering that the final result is obtained by multiplying all the elements in the set , So you should go Conclude Find under category , After browsing all functions under this category , You will find reduce function
list.reduce{
result, item -> result * item }

Scene two :
Suppose you want to find a function that can split a list into several sub lists of fixed size , Consider that the end result is to convert the existing list into another form of set . So you should go Change Search in the category . After reviewing all functions under this category , You will find chunk function
list.chunked(3)

The relationship between categories
above 5 Species category , We can connect them with the concept of state machine , because Creation Categories are used to create collections , So it is the initial state ,Change and Convert It is an intermediate state that can be converted to each other , And the final state is Conclude or Choose. for example :
listOf(1, 2, 3) // Creation
.map {
it * 2 } // Change
.sum() // Conclude
It can also be directly from the initial state to the final state , for example :
listOf(1, 2, 3) // Creation
.sum() // Conclude

Creation
We can Creation Categories are further subdivided , So that we can find the function faster .
- Creation Compose — Instantiate a new set
- Creation Copy — Copy Collection
- Creation Catch — similar try-catch To create a collection
Creation Compose — Instantiate a new set
// Empty set
// Read only set
// Variable set
mutableListOf,mutableMapOf,mutableSetOf,arrayListOf
// Mixed source build collection
// Linked list set
linkedMapOf,linkedSetOf (more in stackOverflow)
// Ordered set
sortedMapOf,sortedSetOf (more in stackOverflow)
// Hash set
hashMapOf, hashSetOf (more in stackOverflow)
// Use code logic to create collections
Creation Copy — Copy Collection
copyInto // Copy the array or its sub range into the target array and return the target array
copyOfRange // Partial reproduction
copyOf // Copy completely
toCollection // Copy to collection
Creation Catch — similar try-catch To create a collection
ifEmpty // If it is blank, the default value will be given
orEmpty // if null Then assign a null value
requireNoNulls // If an element is null Then the program crashes
listOfNotNull // Use all non null Element composition list
Conversion
Conversion The functions under the category are mainly used to change the type of the collection to another type .
We can Conversion Categories are further subdivided , So that we can find the function faster .
- Conversion Copy — Convert to a new set of another type
- Conversion Cite — Convert to another type of original collection reference
A good example is toIntArray (Copy) and asIntArray (Cite):

// toIntArray example (a new copy)
val uIntArray = UIntArray(3) {
1U }
val toIntArray = uIntArray.toIntArray()toIntArray[1] = 2
println(toIntArray.toList()) // [1, 2, 1]
println(uIntArray.toList()) // [1, 1, 1]// asIntArray example (a reference copy)
val uIntArray = UIntArray(3) {
1U }
val asIntArray = uIntArray.asIntArray()
asIntArray[1] = 2
println(asIntArray.toList()) // [1, 2, 1]
println(uIntArray.toList()) // [1, 2, 1]
Conversion Copy — Convert to a new set of another type
// Convert to array type
toBooleanArray,toByteArray,toCharArray,toDoubleArray,toFloatArray,toIntArray,toLongArray,toShortArray,toTypedArray,toUByteArray,toUIntArray,toULongArray,toUShortArray
// Convert to read-only collection
// Convert to variable set
toMutableList,toMutableMap,toMutableSet,toHashSet
// Convert to an ordered set
// turn Entries by Pair
toPair Can be map Of entry Convert to Pair. The sample code is as follows :
map.entries.map {
it.toPair() }
// This is essentially
map.toList()
// Underlying `toList` of Map, it is using `toPair()`
// to do all the conversion of entries to Pair
// turn Map by Properties
toProperties Can be Map convert to Properties(Java Primitive class ), It is Map<String, String> Subclasses of .
val map = mapOf("x" to "value A", "y" to "value B")
val props = map.toProperties()
println(props.getProperty("x")) // value A
println(props.getProperty("z")) // null
println(props.getProperty("y", "fail")) // value B
println(props.getProperty("z", "fail")) // fail
println(map.get("x")) // value A
println(map.get("z")) // null
println(map.getOrDefault("y", "fail")) // value B
println(map.getOrDefault("z", "fail")) // fail
Conversion Cite — Convert to another type of original collection reference
// As an array type
asByteArray,asIntArray,asLongArray,asShortArray,asUByteArray,asUIntArray,asULongArray,asUShortArray,
// As a set type . About list and sequestion, Please read it This article
// To iterator with index
withIndex Can be List Convert to IndexedValue iterable ( Indexed iterable )
val list = listOf("A", "B", "C")
val indexed = list.withIndex()
println(list) // [A, B, C]
println(indexed.toList())
// [IndexedValue(index=0, value=A),
// IndexedValue(index=1, value=B),
// IndexedValue(index=2, value=C)]
// Switch to... With custom defaults Map
withDefault Can be Map Convert to... With custom defaults Map
val map = mutableMapOf(1 to 1)// customize default value return x 2 of keyval default = map.withDefault { k -> k * 2 }println(default.getValue(10)) // return 20println(map.getValue(10)) // crash as no key 10
Change
Change Functions under the category are mainly used to change the content or structure of the set . Further subdivide it :
Change Content ( Change content ): Change the set type and element type , Only change the contents of the set . for example
filterfunction .Change Contour ( Change structure ): Change the set type ( for example ,List perform
groupByThe function will output Map type ) Or change the element type ( for example ,chunkedThe function will change the element type from Int Turn into List<Int>)

Change-Content — Only change the content, not the structure
There are two ways to change the content :
- Create a new set and change the content and return
- Change the original set without returning anything
Take a simple example ,add and plus
val list = listOf(1)val mutableList = mutableListOf(1)println(list) // [1]println(mutableList) // [1]val newList = list.plus(2)mutableList.add(2)println(list) // [1]println(newList) // [1, 2]println(mutableList) // [1, 2]

The purpose of the two functions is the same , But the result is as shown in the figure above , Somewhat different . To distinguish between the two , We use italics to indicate functions such as changing the original set , Such as add, Use normal font to represent another kind of function , Such as plus .
Look at the function list ( Pay attention to distinguish italics )
// Change content
set,setValue //(more info in stackoverflow)
// Add content
plus,plusElement, //(more info in stackoverflow)
plusAssign, //(more info in stackoverflow)
add,addAll,put,putAll
// Remove the content
minus,minusElement, //(more info in stackoverflow)
minusAssign, //(more info in stackoverflow)
remove
// Remove from the head or tail of the set
drop, dropLast, dropLastWhile, dropWhile,removeFirst, removeFirstOrNull, removeLast, removeLastOrNull,

// Select from the head or tail of the set
take, takeLastWhile, takeLast, takeWhile,

// Select from the set

// Only get different ( only ) value

// Given two sets, perform the Wien diagram operation
union, intersect, retainAll, subtract, removeAll

// Convert the element to another value
map, mapTo,mapIndexed, mapIndexedTo,mapKeys, mapKeysTo, mapValues, mapValuesTo, replaceAll, fill
// Will not null Element is converted to another value to ensure that there is no null value
mapNotNull, mapNotNullTo, mapIndexedNotNull, mapIndexedNotNullTo

Be careful :
mapThe function can change List Convert to another structure or another element type , We'll be in the back Change Contour Mentioned in the category .
// Filter some content
filter, filterIndexed, filterIndexedTo, filterIsInstance, filterIsInstanceTo, filterKeys, filterNot, filterNotNull, filterNotNullTo, filterNotTo, filterTo, filterValues

// Reverse content ( Look up This article To distinguish these functions )
reversed,reversedArray, reverse, asReversed

// Sort
sorted, sortedArray, sortedArrayDescending, sortedArrayWith, sortedBy, sortedByDescending, sortedDescending, sortedWithsort, sortBy, sortByDescending, sortDescending, sortWith
// Disrupt the content

// and fold perhaps reduce similar , But the execution process is completed one by one for each element
scan, scanIndexed, scanReduce, scanReduceIndexed

Change Contour — Change both content and structure
The result of such a function will either change the set type , for example List To Map , Or it will change the type of element , for example List<String> To List<Map>.
// Group aggregation formation Map
aggregate, aggregateTo // ( The prerequisites : groupingBy)
// Exampleval numbers = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9)val aggregated = numbers.groupingBy { it % 3 } .aggregate { key, accumulator: Int?, element, first -> if (first) element else accumulator?.plus(element) }println(aggregated) // {1=12, 2=15, 0=18}

// Group count formation Map
eachCount, eachCountTo //( The prerequisites :groupingBy)
// Example Codeval numbers = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9)val eachCount = numbers.groupingBy { it % 2 }.eachCount()println(eachCount) // {1=5, 0=4}

// Use Map key Link each element
associate, associateBy, associateByTo, associateTo, associateWith, associateWithTo //( Look up This article To understand their differences )
// Example codeval list = listOf(1, 2, 3, 4, 5)val associate = list.associateWith { it * it }println(associate) // {1=1, 2=4, 3=9, 4=16, 5=25}

// Group the sets according to rules to form value The type is List Of Map
// Example codeval list = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9)val groupBy = list.groupBy{it % 3}println(groupBy)

// Flatten into a list
// Example codeval map = mapOf(1 to listOf(1, 2), 2 to listOf(2, 4))val flatMap = map.flatMap { it.value }println(flatMap) // [1, 2, 2, 4]// Example codeval list = listOf(listOf(1, 2), listOf(2, 4))val flatten = list.flatten()println(flatten) // [1, 2, 2, 4]

// Change the element to another type
map, mapTo, mapIndexed, mapIndexedTo, mapKeys, mapKeysTo, mapValues, mapValuesTo
// Will not null Element is converted to another type to ensure that there is no null value
mapNotNull, mapNotNullTo, mapIndexedNotNull, mapIndexedNotNullTo
// Example codeval days = listOf("Monday", "Tuesday", "Wednesday", "Thursday")val daysLength = days.map { it.length }println(daysLength)

// Classify elements into different lists
// Example codeval list = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9)val chunked = list.chunked(4)val windowed = list.windowed(4, 3, true)val partition = list.partition { it % 2 == 0 }println(chunked) // [[1, 2, 3, 4], [5, 6, 7, 8], [9]]println(windowed) // [[1, 2, 3, 4], [4, 5, 6, 7], [7, 8, 9]]println(partition)// ([2, 4, 6, 8], [1, 3, 5, 7, 9])

// Combine or disassociate two elements
// Example codeval list = listOf(1, 2, 3, 4, 5)val list2 = listOf(6, 7, 8, 9)val zip = list.zip(list2)println(zip)// Example codeval list = listOf(1, 2, 3, 4)val zipWithNext = list.zipWithNext()println(zipWithNext)// Example codeval list = listOf(1 to 2, 3 to 4, 5 to 6)val unzip = list.unzip()println(unzip)

Choose
Choose Functions under the category are mainly used to access specific elements in the collection , Subdivide it further :
- Choose Certain — Access collection elements according to fixed positions
- Choose Clue — Access collection elements according to given conditions
in any case , The result is one of the elements in the set .
Choose Certain — Access collection elements according to fixed positions
If you think the following functions look similar , The links below will help you distinguish between them
https://levelup.gitconnected.com/kotlin-has-4-ways-to-access-the-collection-element-1cf20cfdd0ed
// It is mainly used for List and Map
get, getOrDefault, getOrElse, getOrNull, getOrPut,getValue // (more info in stackoverflow and check withDefault above)
// It is mainly used for Sequence and Set
elementAt, elementAtOrElse, elementAtOrNull
// For deconstruction
component1, component2, component3, component4, component5
// Random access
// Manual iteration
// Get the unique element in the collection
Choose Clue — Access collection elements according to given conditions
// Find from the first element
// Start with the last element
// Find the index of the element you are looking for
indexOf, lastIndexOf, indexOfFirst, indexOfLast
// Find in an ordered set
Conclude
Conclude Functions under the category mainly generate a result by using the elements in the set according to certain rules , Further refine it :
- Conclude Choice — Judge , for example
isEmpty. - Conclude Compute — Calculation , for example
average. - Conclude Combine — Merge , for example string, hash code.
- Conclude Carryover — Traverse , for example
forEach.
Conclude Choice — Judge
// Presence check
contains, containsAll, containsKey, containsValue
isEmpty, isNotEmpty, isNullOrEmpty ( Look up This article )
// Compare
contentEquals, contentDeepEquals
Conclude Compute — Calculation
// Statistics are relevant
average, count, max, maxBy, maxWith, min, minBy, minWith
sum, sumBy, sumByDouble (double float type)
// apriori computation ( Be similar to scan)
fold, foldIndexed, foldRight, foldRightIndexed, foldTo,
reduce, reduceIndexed, reduceOrNull, reduceRight,
reduceRightIndexed, reduceRightOrNull, reduceTo

Conclude Combine — Merge
// Generate Hash Code
contentHashCode, contentDeepHashCode
// Generate string
contentToString, contentDeepToString, joinTo, joinToString, subarrayContentToString
Conclude Carrayover — Traverse
// Tail circulation
// The middle loop returns the set itself ( Such as side effect function)

Memorandum
in summary , Sort out the memo of all functions for future reference , It can be printed and pasted on the wall

Conclusion
According to the author's classification , I think the tree structure may be more suitable for searching , So I sorted out a mind map .

边栏推荐
- PHP 图片上传
- Redis series 4: sentinel (sentinel mode) with high availability
- Reset grafana login password to default password
- About mit6.828_ HW9_ Some problems of barriers xv6 homework9
- Use js direct OSS to store files in Alibaba cloud and solve the limitation of large file upload server
- 有趣的 Kotlin 0x06:List minus list
- 局域网无法访问apache服务器
- “蔚来杯“2022牛客暑期多校训练营3 A.Ancestor LCA+暴力计数
- Im im development optimization improves connection success rate, speed, etc
- Sort 3-select sort and merge sort (recursive implementation + non recursive implementation)
猜你喜欢

排序1-插入排序与希尔排序

ANSYS secondary development - MFC interface calls ADPL file

ANSA二次开发 - 在PyCharm上搭建ANSA/META二次开发环境

Sort 1-insert sort and Hill sort

Leetcode daily practice - 160. Cross linked list

HyperMesh自动保存(增强版)插件使用说明

关于web对接针式打印机问题,Lodop使用

排序3-选择排序与归并排序(递归实现+非递归实现)

有趣的 Kotlin 0x06:List minus list

使用js直传oss阿里云存储文件,解决大文件上传服务器限制
随机推荐
LeetCode每日一练 —— 160. 相交链表
"Weilai Cup" 2022 Niuke summer multi school training camp 3 h.hacker sam+ segment tree /dp/ divide and conquer (without the largest sub segment and of the inspection interval)
栈的介绍与实现(详解)
有趣的 Kotlin 0x06:List minus list
Leetcode daily practice - 160. Cross linked list
Sdl2 concise tutorial (4): using SDL_ Image library importing pictures
Ansa secondary development - Introduction to interface development tools
HyperMesh自动保存(增强版)插件使用说明
Multiple commands produce '... /xxx.app/assets.car' problem
[pointer internal skill cultivation] character pointer + pointer array + array pointer + pointer parameter (I)
Detailed record of steps to configure web server (many references)
ticdc同步数据怎么设置只同步指定的库?
PHP 图片上传
Kubeedge releases white paper on cloud native edge computing threat model and security protection technology
Redis source code optimization -- binding core
“蔚来杯“2022牛客暑期多校训练营3 J.Journey 0-1最短路
Leetcode topic
CRC16 data verification supports modelbus and XMODEM verification modes (C language)
What does it remote operation and maintenance mean? Which is the best remote operation and maintenance software?
PHP gets the applet code, and the applet jumps with parameters