“This article has participated in the call for good writing activities, click to view: the back end, the big front end double track submission, 20,000 yuan prize pool waiting for you to challenge!”

Original text: medium.com/mobile-app-…

Author: Elye

preface

Do you know how many operation functions Kotlin Collection has? More than 200. It can take a while to go through the alphabetical order of function names, let alone quickly find functions that fit your business scenario, some of which you may not even know exist. Fortunately, I recently read an article about the Kotlin set operating functions. According to the functionality of functions, the author divides them into five categories: Creation, Convert, Change, Choose and Conclude, the author of each category is further divided into subcategories, all types of names begin with C to echo the Collection, feelings like that ah! The quick lookup memo formed by classification makes all functions appear in a tree structure in front of you, making it easier to find. The thoughtful author also provides illustrations for some of the more obscure functions and links to official documentation for some of the more common functions. Thanks to the author’s arrangement, the text begins below.

classification

It is mainly divided into five categories:

  1. Creation: Create a new collection, such as listOf

  2. Convert: Conversion set, such as asMap

  3. Change: changes a set, such as map

  4. Choose: Accesses the set, for example, get

  5. Conclude: Indicates the summary set, for example, sum

How to Find it Quickly

Scene 1:

Suppose you want to find a function that can multiply the values of all integers in a list. Since the result is obtained by multiplying all the elements in the set, you should search under the Conclude category. After browsing all the functions under this category, you will find the Reduce function as you wish

list.reduce{ result, item -> result * item }
Copy the code

Scene 2:

Suppose you want to find a function that splits a list into sublists of a fixed size, considering that the end result is to convert an existing list into a collection of another form. So you should look it up in the Change category. After looking at all the functions under this category, you will find the Chunk function as you wish

list.chunked(3)
Copy the code

Relationships between categories

The Creation category is used to create a collection, so it is the initial state. Change and Convert are intermediate states that can be converted to each other. The final state is Conclude or Choose. Such as:

listOf(1.2.3)   // Creation
.map { it * 2 }   // Change
.sum()            // Conclude
Copy the code

You can also go directly from the initial state to the final state, for example:

listOf(1.2.3)   // Creation
.sum()            // Conclude
Copy the code

Creation

We can further subdivide the Creation category so that we can find functions faster.

  1. Creation Compose – instantiate the new collection
  2. Creation Copy – Replication set
  3. Creation Catch – A try-catch style is used to create collections

Creation Compose – instantiate the new collection

/ / empty collection

emptyList, emptyMap, emptySet

// Read-only collection

listOf, mapOf, setOf

// Variable set

mutableListOf, mutableMapOf, mutableSetOf, arrayListOf

// Mix sources to build collections

buildList, buildMap, buildSet

// Set of linked lists

linkedMapOf, linkedSetOf (more in stackOverflow)

// Ordered set

sortedMapOf, sortedSetOf (more in stackOverflow)

// hash set

hashMapOf, hashSetOf (more in stackOverflow)

// Create a collection using code logic

List, MutableList,Iterable

Creation Copy – Replication set

CopyInto // copies the array or its subscope into the target array and returns the target array

CopyOfRange // Partial copy

CopyOf // Full copy

ToCollection // copy toCollection

Creation Catch – A try-catch style is used to create collections

IfEmpty // Specifies the default value if it is empty

OrEmpty // If null, a null value is assigned

RequireNoNulls // The program crashes if an element is null

ListOfNotNull // uses all non-null elements of the passed argument to form a list

Conversion

Functions under the Conversion category are mainly used to change the type of a collection to another type.

We can further subdivide the Conversion category so that we can find functions faster.

  1. Conversion Copy – A new collection converted to another type
  2. Conversion Cite – An original collection reference that is converted to another type

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)
Copy the code

Conversion Copy – A new collection converted to another type

// Convert to an array type

toBooleanArray, toByteArray, toCharArray, toDoubleArray, toFloatArray, toIntArray, toLongArray, toShortArray, toTypedArray, toUByteArray, toUIntArray, toULongArray, toUShortArray

// Convert to a read-only collection

toList, toMap, toSet

// Convert to a mutable set

toMutableList, toMutableMap, toMutableSet, toHashSet

// Convert to an ordered set

toSortedMap, toSortedSet

// Turn Entries to Pair

toPair

ToPair can convert map entries to pairs. Example 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
Copy the code

// Change Map to Properties

toProperties

ToProperties converts a Map toProperties (Java native class), which is a subclass of Map

.
,>

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
Copy the code

Conversion Cite – An original collection reference that is converted to another type

// as an array type

asByteArray, asIntArray, asLongArray, asShortArray, asUByteArray, asUIntArray, asULongArray, asUShortArray,

// as a collection type. Please refer to this article for list and sequestion

asIterable, asList, asSequence

// Convert to an indexed iterator

withIndex

WithIndex converts List to IndexedValue iterable (iterable withIndex)

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)]
Copy the code

// Convert to Map with custom default values

withDefault

WithDefault converts a Map to a Map with custom default values

val map = mutableMapOf(1 to 1)
// customize default value return x 2 of key
val default = map.withDefault { k -> k * 2 }
println(default.getValue(10)) // return 20
println(map.getValue(10))     // crash as no key 10
Copy the code

Change

Functions under the Change category are mainly used to Change the contents or structure of a collection. To further break it down:

  1. Change Content: Change the collection type and element type, only the Content of the collection. For example, the filter function.

  2. Change Contour: Change the collection type (for example, List execution groupBy will print Map) or Change the element type (for example, chunked will Change the element type from Int to List

    )

Change-content – Just Change the Content, not the structure

There are two ways to change content:

  • Create a new collection and change the contents and return
  • Change the original collection without returning anything

Take a look at 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]
Copy the code

The purpose of the two functions is the same, but the results, as shown above, are different. To distinguish between the two, we use italics for functions that change the original set, such as ***add***, and normal fonts for functions such as plus.

plus, add

Look at the list of functions (note the italics)

// Change the 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 collection

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

slice, sliceArray

// Get only different (unique) values

distinct, distinctBy

// Perform Venn diagram operations on two sets

union, intersect, retainAll, subtract, removeAll

// Convert the element to another value

map, mapTo,mapIndexed, mapIndexedTo,mapKeys, mapKeysTo, mapValues, mapValuesTo, replaceAll, fill

// Convert a non-null element to another value to ensure that there are no null values in the result set

mapNotNull, mapNotNullTo, mapIndexedNotNull, mapIndexedNotNullTo

Note: The map function can convert a List to another structure or to another element type, as we’ll see later in the Change Contour class.

// Filter some content

filter, filterIndexed, filterIndexedTo, filterIsInstance, filterIsInstanceTo, filterKeys, filterNot, filterNotNull, filterNotNullTo, filterNotTo, filterTo, filterValues

// Reverse the contents (see this article to identify the differences between these functions)

reversed,reversedArray, reverse, asReversed

/ / sorting

sorted, sortedArray, sortedArrayDescending, sortedArrayWith, sortedBy, sortedByDescending, sortedDescending, sortedWith sort, sortBy, sortByDescending, sortDescending, sortWith

// Scramble the content

shuffle, shuffled

Similar to fold or reduce, but execution is done on a per-element basis

scan, scanIndexed, scanReduce, scanReduceIndexed

Change Contour – Changes both content and structure

The result of such a function will either change the collection type, such as List to Map, or the element type, such as List<String> to List<Map>.

// Group aggregation to form a Map

Aggregate, aggregateTo // (prerequisite: groupingBy)

// Example
val 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 elseaccumulator? .plus(element) } println(aggregated)/ / {1 = 12, 2 = 15, 0 = 18}
Copy the code

// Group counts to form Map

EachCount, eachCountTo //

// Example Code
val numbers = listOf(1.2.3.4.5.6.7.8.9)
val eachCount = numbers.groupingBy { it % 2 }.eachCount()
println(eachCount) / / {1 = 5, 0 = 4}
Copy the code

// Use the Map key to link each element

Associate, associateBy, associateByTo, associateTo, associateWith, associateWithTo //

// Example code
val 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}
Copy the code

// Group the collection to form a Map of value type List

groupBy, groupByTo

// Example code
val list = listOf(1.2.3.4.5.6.7.8.9)
val groupBy = list.groupBy{it % 3}
println(groupBy)
Copy the code

// Flatten to a list

flatMap, flatMapTo, flatten

// Example code
val 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 code
val list = listOf(listOf(1.2), listOf(2.4))
val flatten = list.flatten()
println(flatten)  // [1, 2, 2, 4]
Copy the code

// Convert the element to another type

map, mapTo, mapIndexed, mapIndexedTo, mapKeys, mapKeysTo, mapValues, mapValuesTo

MapNotNull, mapNotNullTo, mapIndexedNotNull, mapIndexedNotNullTo

// Example code
val days = listOf("Monday"."Tuesday"."Wednesday"."Thursday")
val daysLength = days.map { it.length }
println(daysLength)
Copy the code

// Categorize elements into different lists

chunked, partition, windowed

// Example code
val 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])
Copy the code

// Join or unjoin two elements

zip, zipWithNext, unzip

// Example code
val list = listOf(1.2.3.4.5)
val list2 = listOf(6.7.8.9)
val zip = list.zip(list2)
println(zip)
// Example code
val list = listOf(1.2.3.4)
val zipWithNext = list.zipWithNext()
println(zipWithNext)
// Example code
val list = listOf(1 to 2.3 to 4.5 to 6)
val unzip = list.unzip()
println(unzip)
Copy the code

Choose

Functions under the Choose category are used primarily to access specific elements of the collection, breaking them down further:

  1. Choose Certain – Accesses collection elements based on a fixed position
  2. Choose Clue – Accesses collection elements based on a given condition

In any case, the result is one of the elements in the set.

Choose Certain – Accesses collection elements based on a fixed position

If you think the following functions look similar, the links below will help you distinguish the differences

Levelup.gitconnected.com/kotlin-has-…

// Mainly used for List and Map

get, getOrDefault, getOrElse, getOrNull, getOrPut,getValue // (more info in stackoverflow and check withDefault above)

// Mainly used for Sequence and Set

elementAt, elementAtOrElse, elementAtOrNull

// Used for deconstruction

component1, component2, component3, component4, component5

// Random fetch

random, randomOrNull

// Manually iterate

iterator

// Get the only element in the collection

single, singleOrNull

Choose Clue – Accesses collection elements based on a given condition

// Start with the first element

find, first, firstOrNull

// Start with the last element

findLast, last, lastOrNull

// Find the index of the element being sought

indexOf, lastIndexOf, indexOfFirst, indexOfLast

// Find in the ordered collection

binarySearch, binarySearchBy

Conclude

Functions under the Conclude category generate a result from the elements of the set according to certain rules, which are further refined:

  1. Conclude Choice – A judgment, for exampleisEmpty.
  2. Conclude Compute – Compute, for exampleaverage.
  3. Conclude Combine – Combine, such as string, hash code.
  4. Conclude Carryover – Traversal, for exampleforEach.

Conclude Choice — Make a judgment

// Check the existence

all, any, none

contains, containsAll, containsKey, containsValue

IsEmpty, isNotEmpty, isNullOrEmpty (see here)

/ / to compare

contentEquals, contentDeepEquals

Conclude Compute – Compute

// Statistical correlation

average, count, max, maxBy, maxWith, min, minBy, minWith

sum, sumBy, sumByDouble (double float type)

// Deductive calculation (similar to scan)

fold, foldIndexed, foldRight, foldRightIndexed, foldTo,

reduce, reduceIndexed, reduceOrNull, reduceRight,

reduceRightIndexed, reduceRightOrNull, reduceTo

Conclude Combine – Merge

// Generate Hash Code

contentHashCode, contentDeepHashCode

// Generates a string

contentToString, contentDeepToString, joinTo, joinToString, subarrayContentToString

Conclude Carrayover — Traversal

// tail loop

forEach, forEachIndexed

// The middle loop returns the collection itself (e.g. side effect function)

onEach

The memo

To sum up, sort out all the features of the memo for reference, can be printed and posted on the wall 🙂

conclusion

According to the author’s classification, I felt that tree structure might be more suitable to find, so I put together a mind map.