Function-based Android programming (II): Set Operations in the Kotlin language, androidkotlin
Original article title: Functional Android (II): Collection operations in Kotlin
Link: http://antonioleiva.com/collection-operations-kotlin/
Antonio Leiva (http://antonioleiva.com/about)
Original article published:
Lambda expressions are an outstanding tool to simplify code and can accomplish things that were previously impossible. We talked about them in the first article in this series (Unleash functional power on Android (I): Kotlin Lambdas [translation.
Finally, Lambda expressions are the basis for implementing a large number of function features, as we will discuss today:Set Operations. Kotlin provides a great set of operations that are impossible (or cumbersome) in languages that do not support Lambda expressions ).
This article is not especially about Android, but will push Android APP development in many different ways. Today, I will discuss different types of collections provided by Kotlin and the operations that can be performed on these collections.
Set
Although we can only use Java collections, Kotlin provides a set of good local interfaces that you want to use:
- Iterable: Parent class. Any class inherits this interface to represent elements that can traverse the sequence.
- MutableIterable: Project iterations can be removed during iteration.
- Collection: This class indicates the generic set of elements. We can access the function: return the set size, whether the set is empty, including one or one group. Because the set is unchangeable, all methods of this set can only request data.
- MutableCollection: Supports adding and removing collections of elements. It provides additional functions, such as add, remove, or clear.
- List: Maybe this is the most common set. This indicates an ordered element generic set. Because it is ordered, we can use the get function to request a project based on the project location.
- MutableList: You can add or remove a List of elements.
- Set: Unordered element sets of repeated elements are not supported.
- MutableSet: Supports adding and removing element sets.
- Map: Set of key-value pairs. In a ing table (map), the key (key) is unique, that is, there cannot be two pairs with the same key in a ing table.
- MutableMap: Supports adding and removing Map elements.
Set Operations
This set of function operations can be used for different sets. I want to show you some definitions and examples. It is useful to master these options so that you can easily determine how to use these functions. If any function in the standard function library is missing, please let me know.
All these and more detailed content can be found in the Android developer's Kotlin.
18.1 aggregation operation any
Returns true if at least one element matches the specified condition.
1 val list = listOf(1, 2, 3, 4, 5, 6)2 assertTrue(list.any { it % 2 == 0 })3 assertFalse(list.any { it > 10 })
All
Returns true if all elements match the specified conditions.
1 assertTrue(list.all { it < 10 })2 assertFalse(list.all { it % 2 == 0 })
Count
Returns the number of elements that match the specified condition.
1 assertEquals(3, list.count { it % 2 == 0 })
Fold
The operation results from the first element to the last element of the set are accumulated and the initial value is added.
1 assertEquals(25, list.fold(4) { total, next -> total + next })
FoldRight
It is the same as fold, but it is from the last element to the first element.
1 assertEquals(25, list.foldRight(4) { total, next -> total + next })
ForEach
Perform the specified operation on each element.
1 list forEach { println(it) }
ForEachIndexed
Same as forEach, but also get the index of the element.
1 list forEachIndexed { index, value 2 -> println("position $index contains a $value") }
Max
Returns the largest element. If no element exists, null is returned.
1 assertEquals(6, list.max())
MaxBy
Returns the first element that generates the maximum value for the specified function. If no element exists, null is returned.
1 // The element whose negative is greater2 assertEquals(1, list.maxBy { -it })
Min
Returns the smallest element. If no element exists, null is returned.
1 assertEquals(1, list.min())
MinBy
Returns the first element that generates the minimum value for the specified function. If no element exists, null is returned.
1 // The element whose negative is smaller2 assertEquals(6, list.minBy { -it })
None
Returns true if no element matches the specified condition.
1 // No elements are divisible by 72 assertTrue(list.none { it % 7 == 0 })
Reduce
Same as fold, but not including the initial value. It only accumulates the operation results of the set from the first element to the last element.
1 assertEquals(21, list.reduce { total, next -> total + next })
ReduceRight
Same as reduce, but it is from the last element to the first element.
1 assertEquals(21, list.reduceRight { total, next -> total + next })
SumBy
Returns the sum of the values generated by the element Conversion Function in the set.
1 assertEquals(3, list.sumBy { it % 2 })
18.2 filter operation drop
Returns a list of all elements, excluding the first N.
assertEquals(listOf(5, 6), list.drop(4))
DropWhile
Returns a list of all elements, but does not include the first element that meets the specified conditions.
1 assertEquals(listOf(3, 4, 5, 6), list.dropWhile { it < 3 })
DropLastWhile
Returns a list of all elements, but does not include the last element that meets the specified conditions.
1 assertEquals(listOf(1, 2, 3, 4), list.dropLastWhile { it > 4 })
Filter
Returns a list of all elements that match the specified condition.
1 assertEquals(listOf(2, 4, 6), list.filter { it % 2 == 0 })
FilterNot
Returns a list of all elements that do not match the specified condition.
1 assertEquals(listOf(1, 3, 5), list.filterNot { it % 2 == 0 })
FilterNotNull
Returns a list of all elements, excluding null elements.
1 assertEquals(listOf(1, 2, 3, 4), listWithNull.filterNotNull())
Slice
Returns the list of elements of the specified index.
1 assertEquals(listOf(2, 4, 5), list.slice(listOf(1, 3, 4)))
Take
Returns the list of the first N elements.
1 assertEquals(listOf(1, 2), list.take(2))
TakeLast
Returns the list of the last N elements.
1 assertEquals(listOf(5, 6), list.takeLast(2))
TakeWhile
Returns the list of the first element that meets the specified conditions.
1 assertEquals(listOf(1, 2), list.takeWhile { it < 3 })
18.3 ing operation flatMap
Create a new set by traversing each element, and then integrate all sets into a unique list containing all elements.
1 assertEquals(listOf(1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7), list.flatMap { listOf(it, it + 1) })
GroupBy
Returns a ing table that contains elements that are grouped by the specified function in the original set.
1 assertEquals(mapOf("odd" to listOf(1, 3, 5), "even" to listOf(2, 4, 6)), list.groupBy { if (it % 2 == 0) "even" else "odd" })
Map
Returns a list that contains the converted results for each element in the original set.
1 assertEquals(listOf(2, 4, 6, 8, 10, 12), list.map { it * 2 })
MapIndexed
Returns a list of converted elements and their indexes in the original set.
1 assertEquals(listOf (0, 2, 6, 12, 20, 30), list.mapIndexed { index, it -> index * it })
MapNotNull
Returns a list of non-null elements in the original set.
1 assertEquals(listOf(2, 4, 6, 8), listWithNull mapNotNull { it * 2 })
18.4 element operation contains
Returns true if a specified element is found in the collection.
1 assertTrue(list.contains(2))
ElementAt
Returns the element at the specified index position. If the index exceeds the range of this set, IndexOutOfBoundsException is thrown.
1 assertEquals(2, list.elementAt(1))
ElementAtOrElse
Returns the element at the specified index position. If the index exceeds the range of this set, the result of calling the default function is returned.
1 assertEquals(20, list.elementAtOrElse(10, { 2 * it }))
ElementAtOrNull
Returns the element at the index position. If the index exceeds the range of this set, null is returned.
1 assertNull(list.elementAtOrNull(10))
First
Returns the first element that matches the specified condition.
1 assertEquals(2, list.first { it % 2 == 0 })
FirstOrNull
Returns the first element that matches the specified condition. If no matching element is found, null is returned.
1 assertNull(list.firstOrNull { it % 7 == 0 })
IndexOf
Returns the index of the first element. -1 is returned if the set does not contain any element.
1 assertEquals(3, list.indexOf(4))
IndexOfFirst
Returns the first element index that matches the specified condition. If the set does not contain such an element,-1 is returned.
1 assertEquals(1, list.indexOfFirst { it % 2 == 0 })
IndexOfLast
Returns the last element index that matches the specified condition. If the set does not contain such an element,-1 is returned.
1 assertEquals(5, list.indexOfLast { it % 2 == 0 })
Last
Returns the last element that matches the specified condition.
1 assertEquals(6, list.last { it % 2 == 0 })
LastIndexOf
Returns the index of the last element. If the set does not contain elements,-1 is returned.
1 val listRepeated = listOf(2, 2, 3, 4, 5, 5, 6)2 assertEquals(5, listRepeated.lastIndexOf(5))
LastOrNull
Returns the last element that matches the specified condition. If such an element is not found, null is returned.
1 val list = listOf(1, 2, 3, 4, 5, 6)2 assertNull(list.lastOrNull { it % 7 == 0 })
Single
Returns a single element that matches the specified condition. If no or multiple elements match, an exception is thrown.
1 assertEquals(5, list.single { it % 5 == 0 })
SingleOrNull
Returns a single element that matches the specified condition. If no such element is found or multiple such elements are found, null is returned.
1 assertNull(list.singleOrNull { it % 7 == 0 })
18.5 generate merge
Returns a list consisting of two sets with the same index element converted by the conversion function. The length of the list is the length of the largest set.
1 val list = listOf(1, 2, 3, 4, 5, 6)2 val listRepeated = listOf(2, 2, 3, 4, 5, 5, 6)3 assertEquals(listOf(3, 4, 6, 8, 10, 11), list.merge(listRepeated) { it1, it2 -> it1 + it2 })
Partition
Split the original set into a pair of sets. One set contains elements with true judgment conditions, and the other contains elements with false judgment conditions.
1 assertEquals(Pair(listOf(2, 4, 6), listOf(1, 3, 5)), list.partition { it % 2 == 0 })
Plus
Returns a list containing all elements of the original set and all elements of the specified set. For the function name, we can use the "+" operator.
1 assertEquals(listOf(1, 2, 3, 4, 5, 6, 7, 8), list + listOf(7, 8))
Zip
Returns a list of element pairs created by the same index elements in two sets. The list length is the length of the shortest set.
1 assertEquals(listOf(Pair(1, 7), Pair(2, 8)), list.zip(listOf(7, 8)))
18.6 sorting operation reverse
Returns the list of reverse elements.
1 val unsortedList = listOf(3, 2, 7, 5)2 assertEquals(listOf(5, 7, 2, 3), unsortedList.reverse())
Sort
Returns the sorting list of all element categories.
1 assertEquals(listOf(2, 3, 5, 7), unsortedList.sort())
SortBy
Returns a list of all elements sorted by a specific comparator.
1 assertEquals(listOf(3, 7, 2, 5), unsortedList.sortBy { it % 3 })
SortDescending
Returns the sorting list of all elements in descending order.
1 assertEquals(listOf(7, 5, 3, 2), unsortedList.sortDescending())
SortDescendingBy
Returns the sort list of all elements in descending order of the result of a specific sort function.
1 assertEquals(listOf(2, 5, 7, 3), unsortedList.sortDescendingBy { it % 3 })
Previous Article: http://www.cnblogs.com/figozhg/p/5021725.html