Original title: Functional Android (II): Collection operations in Kotlin
Original link:http://antonioleiva.com/collection-operations-kotlin/
Original Antonio Leiva (http://antonioleiva.com/about/)
Published in the original: 2015-09-29
In terms of simplifying code, lambda expressions are an excellent tool and can accomplish things that are not possible before. We talked about them in the first article in this series (unleash functional Power on Android (I): Kotlin Lambdas [ translated ]).
Finally, lambda expressions are the basis for implementing a large number of function features, as we will discuss today: collection Operations . Kotlin provides a great set of operations that are not possible (or cumbersome) in languages that do not support lambda expressions.
This article is not specifically for Android, but will drive Android app development in many different ways. Today, I will discuss the different types of collections that Kotlin provides, and the operations that can be performed on those collections.
Collection
While we can use only Java collections, Kotlin provides a good native interface that you want to use:
- iterable: Parent class. Any class that inherits this interface represents an element that can traverse the sequence.
- mutableiterable: Supports removing iterations of a project during an iteration.
- Collection: This class represents a generic collection of elements. We can access the function: Returns the collection size, whether the collection is empty, contains one or a group. Because the collection is immutable, all methods of such a collection can only request data.
- mutablecollection: Supports the addition and removal of collection elements. It provides additional functions such as add, remove, or clear, and so on.
- List: Perhaps this is the most commonly used collection. This represents an ordered set of element generics. Because it is ordered, we can use the Get function to request items according to the location of the project.
- mutablelist: A list that supports adding and removing elements.
- Set: A collection of unordered elements that do not support repeating elements.
- Mutableset: Supports adding and removing set of elements.
- Map: Key-value (Key-value) pair collection. The key (key) is unique in the mapping table (map), meaning that no two pairs have the same key in a mapping table.
- Mutablemap: A map that supports adding and removing elements.
Collection Operations
This set of function actions can be used for different collections. I want to show you some definitions and examples. It is useful to master these options, which makes it easy to determine how to use these functions. Please let me know if there are any functions missing from the standard library of functions.
All these and more details can be found in theAndroid Developer's Kotlinbook.
18.1Aggregation Operations any
Returns true if at least one element matches the specified criteria.
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 criteria.
1 asserttrue (List.all {It < ten })2 assertfalse (List.all {it% 2 = = 0})
Count
Returns the number of elements that match the specified criteria.
1 assertequals (3, List.count {it% 2 = = 0})
Fold
The result of the operation of the collection from the first to the last element is incremented and the initial value is added.
1 assertequals (List.fold (4) {Total, Next and Total + next})
Foldright
With fold, however, is from the last element to the first element.
1 assertequals (List.foldright (4) {Total, Next and Total + next})
ForEach
Performs the specified action on each element.
1 list ForEach {println (IT)}
foreachindexed
Same as foreach, but also gets the index of the element.
12 -println ("position $index contains a $value")}
Max
Returns the largest element. If there are no elements, NULL is returned.
1 assertequals (6, List.max ())
Maxby
Returns the first element that causes the specified function to produce a maximum value. If there are no elements, NULL is returned.
1 // The element whose negative is greater 2 assertequals (1, List.maxby {-it})
min
Returns the smallest element, or null if there are no elements.
1 assertequals (1, list.min ())
Minby
Returns the first element that causes the specified function to produce a minimum value. If there are no elements, NULL is returned.
1 // The element whose negative is smaller 2 assertequals (6, List.minby {-it})
None
Returns true if no element matches the specified criteria.
1 // No Elements is divisible by 7 2 asserttrue (List.none {it% 7 = = 0})
Reduce
Same as fold, but does not include the initial value. Only the result of the operation of the collection from the first element to the last element is accumulated.
1 assertequals (+, List.reduce {Total, Next and Total + next})
Reduceright
With reduce, however, is from the last element to the first element.
1 assertequals (+, List.reduceright {Total, Next and Total + next})
Sumby
Returns the sum of the values generated by the element-in conversion function in the collection.
1 assertequals (3, List.sumBy {it% 2})
18.2Filtering ActionsDrop
Returns a list of all elements, but excludes the first n elements.
Assertequals (Listof (5, 6), List.drop (4))
Dropwhile
Returns a list of all elements, but does not include the first element that satisfies the specified criteria.
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 satisfies the specified criteria.
1 assertequals (Listof (1, 2, 3, 4), List.droplastwhile {it > 4})
Filter
Returns a list of all elements that match the specified criteria.
1 assertequals (Listof (2, 4, 6), List.filter {it% 2 = = 0})
Filternot
Returns a list of all elements that do not match the specified criteria.
1 assertequals (Listof (1, 3, 5), List.filternot {it% 2 = = 0})
Filternotnull
Returns a list of all elements, but does not include a null element.
1 assertequals (Listof (1, 2, 3, 4), Listwithnull.filternotnull ())
Slice
Returns a list of elements for the specified index.
1 assertequals (Listof (2, 4, 5), List.slice (Listof (1, 3, 4))
Take
Returns a list of the first n elements.
1 assertequals (Listof (1, 2), List.take (2))
Takelast
Returns a list of the last n elements.
1 assertequals (Listof (5, 6), List.takelast (2))
TakeWhile
Returns a list of the first elements that meet the specified criteria.
1 assertequals (Listof (1, 2), List.takewhile {it < 3})
18.3Mapping OperationsFlatMap
Create a new collection by traversing through each element, and finally, consolidate all the collections into a unique list that contains all the 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 mapping table that includes elements that are grouped by the specified function on the elements in the original collection.
1 assertequals (mapof ("odd" to Listof (1, 3, 5), "even" to Listof (2, 4, 6ifelse "odd"})
Map
Returns a list that contains the converted results for each element in the original collection.
1 assertequals (Listof (2, 4, 6, 8, ten), List.map {it * 2})
mapindexed
Returns a list that contains the converted results and their indexes for each element in the original collection.
1 assertequals (listof (0, 2, 6,, +), list.mapindexed {index, it--index * It})
Mapnotnull
Returns a list that contains the results of converting non-null elements to the original collection.
1 assertequals (Listof (2, 4, 6, 8), Listwithnull mapnotnull {it * 2})
18.4element Manipulationcontains
Returns true if the 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 collection, Indexoutofboundsexception is thrown.
1 assertequals (2, List.elementat (1))
Elementatorelse
Returns the element at the specified index position. Returns the result of calling the default function if the index is outside the scope of this collection.
1 assertequals (List.elementatorelse (Ten, {2 * it}))
Elementatornull
Returns the element of the index position. If the index exceeds the range of this collection, NULL is returned.
1 assertnull (List.elementatornull (10))
First
Returns the first element that matches the specified criteria.
1 assertequals (2, List.first {it% 2 = = 0})
Firstornull
Returns the first element that matches the specified criteria. If no matching element is found, NULL is returned.
1 assertnull (list.firstornull {it% 7 = = 0})
indexOf
Returns the index of the first element. Returns 1 if the collection contains no elements.
1 assertequals (3, List.indexof (4))
Indexoffirst
Returns the first index of an element that matches the specified criteria. Returns 1 if the collection does not contain such an element.
1 assertequals (1, List.indexoffirst {it% 2 = = 0})
Indexoflast
Returns the last element index that matches the specified criteria. Returns 1 if the collection does not contain such an element.
1 assertequals (5, List.indexoflast {it% 2 = = 0})
Last
Returns the last element that matches the specified criteria.
1 assertequals (6, List.last {it% 2 = = 0})
lastIndexOf
Returns the last element index. Returns 1 if the collection does not contain an element.
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 criteria. If no such element is 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 criteria. Throws an exception if there are no or multiple matching elements.
1 assertequals (5, List.single {it% 5 = = 0})
Singleornull
Returns a single element that matches the specified criteria. If no such element is found or if more than one such element is found, then NULL is returned.
1 assertnull (list.singleornull {it% 7 = = 0})
18.5Build ActionMerge
Returns a list of two collections that have the same index elements converted by conversion functions. The length of this list is the length of the maximum set.
1 val list = Listof (1, 2, 3, 4, 5, 6)2 val listrepeated = Listof (2, 2, 3, 4, 5, 5, 6) C4>3 assertequals (Listof (3, 4, 6, 8, ten, one), List.merge (listrepeated) {it1, it2 it1 + it2})
Partition
Splits the original collection into a pair of collections, one containing an element that evaluates to true, and another that contains elements that determine the condition to be false.
1 assertequals (Pair (Listof (2, 4, 6), Listof (1, 3, 5)), list.partition {it% 2 = = 0})
Plus
Returns a list that contains all the elements of the original collection and all the elements of the specified collection. Because of the function name reason, 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 the pairs of elements established by the same indexed elements in the two collection. The length of this list is the shortest set length.
1 assertequals (Listof (Pair (1, 7), pair (2, 8)), List.zip (Listof (7, 8))
18.6Sort OperationsReverse
Returns a list of reverse elements.
1 val unsortedlist = Listof (3, 2, 7, 5)2 assertequals (Listof (5, 7, 2, 3), Unsortedlist.reverse ( ))
Sort
Returns a sorted list of all element classifications.
1 assertequals (Listof (2, 3, 5, 7), Unsortedlist.sort ())
SortBy
Returns a list of all elements whose elements are sorted by a particular comparer.
1 assertequals (Listof (3, 7, 2, 5), Unsortedlist.sortby {it% 3})
sortdescending
Returns a sorted list of all element classifications, in descending order.
1 assertequals (Listof (7, 5, 3, 2), unsortedlist.sortdescending ())
Sortdescendingby
Returns a sorted list of all the elements, in descending order of the result of a particular sort function.
1 assertequals (Listof (2, 5, 7, 3), Unsortedlist.sortdescendingby {it% 3})
Previous article:http://www.cnblogs.com/figozhg/p/5021725.html
Functional Android Programming (II): Set operations for Kotlin languages