当前位置:网站首页>Set functions in kotlin
Set functions in kotlin
2022-07-29 03:30:00 【0 cute 0】
This article will introduce some Kotlin Set function , These functions can greatly improve our development efficiency , It can be read as a cheat sheet at any time ~
Delete array Duplicate string in
There are many ways to remove duplicate strings from an array :
// Keep the original order of elements
val devs = arrayOf("Amit", "Ali", "Amit", "Sumit", "Sumit", "Himanshu")
print(devs.distinct()) // [Amit, Ali, Sumit, Himanshu]
// Keep the original order of elements
val devs = arrayOf("Amit", "Ali", "Amit", "Sumit", "Sumit", "Himanshu")
print(devs.toSet()) // [Amit, Ali, Sumit, Himanshu]
// Keep the original order of elements
val devs = arrayOf("Amit", "Ali", "Amit", "Sumit", "Sumit", "Himanshu")
print(devs.toMutableSet()) // [Amit, Ali, Sumit, Himanshu]
// The original order of elements is not preserved
val devs = arrayOf("Amit", "Ali", "Amit", "Sumit", "Sumit", "Himanshu")
print(devs.toHashSet()) // [Amit, Ali, Sumit, Himanshu]
** take array To list perhaps string **
You can use joinToString Function will list To string . for example , There is a list of cities (Delhi, Mumbai, Bangalore),, Then you can turn the list into such a string : “India is one the best country for tourism. You can visit Delhi, Mumbai, Bangalore, etc, and enjoy your holidays”.
val someKotlinCollectionFunctions = listOf(
"distinct", "map",
"isEmpty", "contains",
"filter", "first",
"last", "reduce",
"single", "joinToString"
)
val message = someKotlinCollectionFunctions.joinToString(
separator = ", ",
prefix = "Kotlin has many collection functions like: ",
postfix = "and they are awesome.",
limit = 3,
truncated = "etc "
)
print(message)
Kotlin There are also many great functions , such as distinct, map, isEmpty, wait
Turn a set into a single result
If you want to convert a given set into a single result , have access to rudece function . For example, you can sum all the elements in the list :
val numList = listOf(1, 2, 3, 4, 5)
val result = numList.reduce {
result, item ->
result + item
}
print(result) // 15
// Be careful : If the list is empty , Will throw out RuntimeException
Determine whether all elements meet specific conditions
If you have an array or list , You want to know whether all the elements meet a certain condition , have access to all function :
data class User(val id: Int, val name: String, val isCricketLover: Boolean, val isFootballLover: Boolean)
val user1 = User(id = 1, name = "Amit", isCricketLover = true, isFootballLover = true)
val user2 = User(id = 2, name = "Ali", isCricketLover = true, isFootballLover = true)
val user3 = User(id = 3, name = "Sumit", isCricketLover = true, isFootballLover = false)
val user4 = User(id = 4, name = "Himanshu", isCricketLover = true, isFootballLover = false)
val users = arrayOf(user1, user2, user3, user4)
val allLoveCricket = users.all {
it.isCricketLover }
print(allLoveCricket) // true
val allLoveFootball = users.all {
it.isFootballLover }
print(allLoveFootball) // false
Find an element that meets the given conditions
You can use find Function finds an element in the list that meets the given condition . such as , Find in a student list id yes 5 Of the students .find The function returns the first element that matches the given condition , If not found , Returns the null.single The function returns the only element that matches the given condition , If there are multiple elements that meet the conditions or there are no elements that meet the conditions , It throws an exception :
data class User(val id: Int, val name: String)
val users = arrayOf(
User(1, "Amit"),
User(2, "Ali"),
User(3, "Sumit"),
User(4, "Himanshu")
)
val userWithId3 = users.single {
it.id == 3 }
print(userWithId3) // User(id=3, name=Sumit)
val userWithId1 = users.find {
it.id == 1 }
print(userWithId1) // User(id=1, name=Amit)
Split the list into smaller lists
When you have a larger list , Want to split it into multiple sub lists , Then do some operations on these sub lists . At this time , have access to chunked function :
val numList = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
val chunkedLists = numList.chunked(3)
print(chunkedLists) // [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]
Copy the array
You can use these functions to copy existing arrays :
- copyInto: This function will copy the elements of the specified range of its own array to the specified position of another array , If the target array subscript is out of bounds , An array subscript out of bounds exception will be thrown :
val arrayOne = arrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
val arrayTwo = arrayOf(11, 12, 13, 14, 15, 16, 17, 18, 19, 20)
arrayOne.copyInto(destination = arrayTwo, destinationOffset = 2, startIndex = 0, endIndex = 4)
arrayTwo.forEach {
print("$it ")} // 11 12 1 2 3 4 17 18 19 20
Similarly , There are other functions that can copy array elements , for example :
- copyOfRange(fromIndex, toIndex): Returns a new array that copies the elements of the specified range of the original array
- copyOf() or copyOf(newSize): Returns a copy of the original array with a length of newSize New array , If not specified newSize, Copy the entire array by default .
Change the type of set
You can change the type of set according to the situation . You can create a new set of other types by referencing the old set :
toIntArray, toBooleanArray, toLongArray, toShortArray, toByteArray, toDoubleArray, toList, toMap, toSet, toPair, And other functions can change the type of set etc can be used to change the type of one collection to another type.
var uIntArray = UIntArray(5) {
1U }
var intArray = uIntArray.toIntArray()
intArray[0] = 0
print(uIntArray.toList()) // [1, 1, 1, 1, 1]
print(intArray.toList()) // [0, 1, 1, 1, 1]
Here we create a new set and merge and change the elements in the new set , This will not affect the collection . meanwhile , We can also hold references to old sets to change the set type , Changing one set will affect the other set . Like this with as Function of prefix :asIntArray, asLongArray, asShortArray, asByteArray, asList wait :
var uIntArray = UIntArray(5) {
1U }
var intArray = uIntArray.asIntArray()
intArray[0] = 0
print(uIntArray.toList()) // [0, 1, 1, 1, 1]
print(intArray.toList()) // [0, 1, 1, 1, 1]
take key Associated with data
If you have a list of data , I want to compare the data with key Connect , have access to associateBy function :
data class Contact(val name: String, val phoneNumber: String)
val contactList = listOf(
Contact("Amit", "+9199XXXX1111"),
Contact("Ali", "+9199XXXX2222"),
Contact("Himanshu", "+9199XXXX3333"),
Contact("Sumit", "+9199XXXX4444")
)
val phoneNumberToContactMap = contactList.associateBy {
it.phoneNumber }
print(phoneNumberToContactMap)
// Map with key: phoneNumber and value: Contact
// {
// +9199XXXX1111=Contact(name=Amit, phoneNumber=+9199XXXX1111),
// +9199XXXX2222=Contact(name=Ali, phoneNumber=+9199XXXX2222),
// +9199XXXX3333=Contact(name=Himanshu, phoneNumber=+9199XXXX3333),
// +9199XXXX4444=Contact(name=Sumit, phoneNumber=+9199XXXX4444)
// }
In the example above ,key yes phoneNumber ,value yes Contact. If you don't want to put the whole Contact As value, Then you can pass on your expectations like this :
val phoneNumberToContactMap = contactList.associateBy({
it.phoneNumber}, {
it.name})
print(phoneNumberToContactMap)
// Map with key: phoneNumber and value: name
// {
// +9199XXXX1111=Amit,
// +9199XXXX2222=Ali,
// +9199XXXX3333=Himanshu,
// +9199XXXX4444=Sumit}
// }
Find the only element in the collection
We can call distinct Function to get the unique set of elements in the list
val list = listOf(1, 2, 2, 3, 3, 3, 4, 4, 4, 4)
println(list.distinct()) // [1, 2, 3, 4]
Joint set
call union Function can get the only element in two sets , The order of elements in the original set will also be preserved , The elements of the second set will be added to the elements of the first set
val listOne = listOf(1, 2, 3, 3, 4, 5, 6)
val listTwo = listOf(2, 2, 4, 5, 6, 7, 8)
println(listOne.union(listTwo)) // [1, 2, 3, 4, 5, 6, 7, 8]
Take the intersection of sets
In order to get the elements common to two sets , have access to intersect function , It returns the set of common elements that appear in both sets
val listOne = listOf(1, 2, 3, 3, 4, 5, 6)
val listTwo = listOf(2, 2, 4, 5, 6, 7, 8)
println(listOne.intersect(listTwo)) // [2, 4, 5, 6]
Keep only specific elements
Use retainAll Functions retain specific elements , This function will modify the original list , So make sure that the list or array can be modified
If an element is deleted from the list ,retainAll Returns the true, Otherwise it will return to false
val listOne = mutableListOf(1, 2, 3, 3, 4, 5, 6)
val listTwo = listOf(1, 2, 3, 3, 4, 5, 6)
val listThree = listOf(1, 2, 3, 3, 4, 5, 7)
println(listOne.retainAll(listTwo)) // false
println(listOne.retainAll(listThree)) // true
println(listOne) // [1, 2, 3, 3, 4, 5]
Similarly , Use removeAll Function can delete elements in a set that appear in another set .
Filter sets based on conditions filter Function can filter out elements in the set that do not meet the specified conditions , It will return a list of all elements that meet this condition :
val list = listOf(1, 2, 3, 4, 5, 6, 7, 8)
val filteredList = list.filter {
it % 2 == 0 }
print(filteredList) // [2, 4, 6, 8]
filterIndexed You can filter elements based on subscripts . If you want to save the filtered elements in a collection , that , use filterIndexedTo Function :
val list = listOf(1, 2, 3, 4, 5, 6, 7, 8)
val filteredList = mutableListOf<Int>()
list.filterIndexedTo(filteredList) {
index, i -> list[index] % 2 == 0 }
print(filteredList) // [2, 4, 6, 8]
You can use filterIsInstance Function to filter out elements that meet specific types of instances :
val mixedList = listOf(1, 2, 3, "one", "two", 4, "three", "four", 5, 6, "five", 7)
val strList = mixedList.filterIsInstance<String>()
print(strList) // [one, two, three, four, five]
Compress the set zip Function returns a list of two tuples , The first element of a two tuple is taken from the first set , The second element song, the second set . The length of the returned list is equal to the length of the shorter of the two sets :
val listOne = listOf(1, 2, 3, 4, 5)
val listTwo = listOf("a", "b", "c", "d", "e", "f")
print(listOne zip listTwo) // [(1, a), (2, b), (3, c), (4, d), (5, e)]
zipWithNext Function returns a list of two tuples , The elements of two tuples are composed of adjacent elements in the set :
val list = listOf(1, 2, 3, 4, 5)
print(list.zipWithNext()) // [(1, 2), (2, 3), (3, 4), (4, 5)]
Decompress the collection unzup Function returns a list Binary , The first list in a tuple consists of the first element of a two tuple in the original set , The second element consists of the second tuple in the original set :
val list = listOf("Amit" to 8, "Ali" to 10, "Sumit" to 4, "Himanshu" to 2)
val (players, footballSkills) = list.unzip()
print(players) // [Amit, Ali, Sumit, Himanshu]
print(footballSkills) // [8, 10, 4, 2]
Divide the array into two parts
If you want to divide an array into two parts by some conditions ,partition Function can meet the requirements :
data class User(val id: Int, val name: String, val isFootballLover: Boolean)
val users = listOf(
User(1, "Amit", true),
User(2, "Ali", true),
User(3, "Sumit", false),
User(4, "Himanshu", false)
)
val (footballLovers, nonFootballLovers) = users.partition {
it.isFootballLover }
print(footballLovers) // [User(id=1, name=Amit, isFootballLover=true), User(id=2, name=Ali, isFootballLover=true)]
print(nonFootballLovers) // [User(id=3, name=Sumit, isFootballLover=false), User(id=4, name=Himanshu, isFootballLover=false)]
Reverse list reversed Functions and asReversed Function can reverse the list . The difference is :reversed It can be applied to Array, List, and MutableList On , Function returns a new list after inversion ; asReversed It can be used for List, and MutableList On , The list returned by the function still refers to the old list , Change one of them , Will affect another list :
val list = listOf(1, 2, 3, 4, 5)
print(list.reversed()) // [5, 4, 3, 2, 1]
print(list.asReversed()) // [5, 4, 3, 2, 1]
Similarly , also reversedArray,reverse Two functions .
Group collection elements groupBy Function can group set elements based on a certain condition :
val list = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
print(list.groupBy {
it % 4 })
// {
// 1=[1, 5, 9],
// 2=[2, 6, 10],
// 3=[3, 7],
// 0=[4, 8]
// }
Sort collection elements sorted Function can sort collection elements , And return a sorted list :
val list = listOf(10, 4, 1, 3, 7, 2, 6)
print(list.sorted()) // [1, 2, 3, 4, 6, 7, 10]
besides , There are also many sorting functions , Such as :sortedArray, sortedArrayWith, sortedBy, sortedByDescending, sortedArraydescending, sortedWith wait .
边栏推荐
- Whole process record of yolov3 target detection
- HDU多校第二场 1011 DOS Card
- Sleuth+zipkin to track distributed service links
- Matlab learning - accumulation of small knowledge points
- CUDA GDB prompt: /tmp/tmpxft**** cudafe1.stub. c: No such file or directory.
- ROS-Errror:Did you forget to specify generate_ messages(DEPENDENCIES ...)?
- Ten thousand words detailed Google play online application standard package format AAB
- July 28, 2022 Gu Yujia's study notes
- Score addition and subtraction of force deduction and brushing questions (one question per day 7/27)
- 腾讯云使用pem登录
猜你喜欢

Tonight at 7:30 | is the AI world in the eyes of Lianjie, Jiangmen, Baidu and country garden venture capital continue to be advanced or return to the essence of business

During the year, the first "three consecutive falls" of No. 95 gasoline returned to the "8 Yuan era"“

逐步分析类的拆分之案例——五彩斑斓的小球碰撞

MYCAT read / write separation configuration

Example analysis of while, repeat and loop loops in MySQL process control

How to deploy sentinel cluster of redis

Various minor problems of jupyter notebook, configuration environment, code completion, remote connection, etc

美联储再加息,75基点 鲍威尔“放鸽”,美股狂欢

How to solve the time zone problem in MySQL timestamp

Design of smoke temperature, humidity and formaldehyde monitoring based on single chip microcomputer
随机推荐
今晚7:30 | 连界、将门、百度、碧桂园创投四位大佬眼中的AI世界,是继续高深还是回归商业本质?...
Practical guidance for interface automation testing (Part I): what preparations should be made for interface automation
Introduction and advanced MySQL (13)
What is eplato cast by Plato farm on elephant swap? Why is there a high premium?
年内首个“三连跌” 95号汽油回归“8元时代“
C obtains JSON format data asynchronously from the web address
深入C语言(1)——操作符与表达式
Simple code implementation of K-means clustering
2 neural network toolbox NN
How to judge stun protocol
C language programming | exchange binary odd and even bits (macro Implementation)
Numpy acceleration -- > cupy installation
Bingbing learning notes: operator overloading -- implementation of date class
Various minor problems of jupyter notebook, configuration environment, code completion, remote connection, etc
深入C语言(2)——结构的定义与使用
for_each用法示例
Summary of basic knowledge points of C language
MOS管 —— 快速复苏应用笔记(贰)[参数与应用]
Arm architecture and neural network
LeetCode 1331 数组序号转换[Map] HERODING的LeetCode之路