当前位置:网站首页>Kotlin: collection use
Kotlin: collection use
2022-07-04 09:46:00 【There is a beauty like jade in the book】
Set is mainly List、Set、Map, They are Java There are interfaces in ,
List --> ArrayList、LinkedList
Set --> HashSet
Map–> HashMap
1、List Set initialization
stay Kotlin Generally, this is the way to initialize a set in :
val list = ArrayList<String>()
list.add("1")
list.add("2")
This is very cumbersome , So here we will introduce list Several methods of :listof()、mutableListOf()
val list = listOf("aa", "bb")
val list = mutableListOf("aa", "bb")
listof(): What is created is an immutable set , This collection can only be used to read data , Set data cannot be added, deleted or modified .
mutableListOf(): What is created is a variable set , You can add, delete, modify and query .
Traverse List The collection needs to use for-in Loop through , such as :
fun main(){
val list1 = listOf("aa", "bb")
for (content in list1){
content.toUpperCase()// Capitalize the traversal content
print(content)
}
val list2 = mutableListOf("aa", "bb")
list2.add("cc")
for (content in list2){
content.toUpperCase()// Capitalize the traversal content
print(content)
}
}
2、Set aggregate
Set and List The usage of is actually the same , These methods will be used during initialization :setof()、mutableSetOf()
val set = setOf("aa", "bb")
val set = mutableSetOf("aa", "bb")
setof(): What is created is an immutable set , This collection can only be used to read data , Set data cannot be added, deleted or modified .
mutableSetOf(): What is created is a variable set , You can add, delete, modify and query .
ad locum ,Set aggregate List The difference between sets needs to be noted ,Set The bottom layer is to use Hash Mapping mechanism to store data , Therefore, the elements in the collection cannot be guaranteed to be orderly .
---- Ergodic and List equally , No explanation
3、Map Set initialization
Map Gather here to focus on ,Map Different from the first two ,Map Is a data structure in the form of key value pairs , Therefore, in usage and List、Set There's a big difference .
General initialization Map You need to create a HashMap
val map = HashMap<String, String>()
map.put("aa", "1")
map.put("bb", "2")
Because in Kotlin in , Not recommended put()、get() Method pair Map Add and read data , Instead, use this subscript like method to add data :
val map = HashMap<String, String>()
map["aa"] = 1
map["bb"] = 2
When the data is read
val text = map["aa"]
However , The above method of adding data is still very cumbersome , and List、Set equally ,Map It has its own way mapof()、mutableMapOf()
val map1 = mapOf("aa" to 1, "bb" to 2) // immutable
val map2 = mutableMapOf("aa" to 1, "bb" to 2) // variable
mapof(): What is created is an immutable set , This collection can only be used to read data , Set data cannot be added, deleted or modified .
mutableMapOf(): What is created is a variable set , You can add, delete, modify and query .
Traverse Map aggregate , Also used for-in loop , The only difference is that ,for-in In circulation ,map The key value pair and the variable are declared in a pair of brackets
fun main(){
val map1 = mapOf("aa" to 1, "bb" to 2)
for ((content1, content2) in map1){
print(content1 + "--" + content2)
}
}
4、 Set function API(lambda)
First define a set , Then find the element with the longest length inside
val list1 = listOf("aa", "bbbb", "cc")
var maxLength = ""
for (content in list1){
if (content.length > maxLength.length){
maxLength = content
}
}
print(maxLength)
The traditional way is usually written like this , But for the function of set API, You can make this function more brief
val list1 = listOf("aa", "bbbb", "cc")
var maxLength = list1.maxBy { it.length }
print(maxLength)
This is the function API Usage of , Just one line of code can handle .
Next, let's take a look at the derivation process :
First of all, let's get to know lambda Expression structure :
{ Parameter name 1: Parameter type , Parameter name 2: Parameter type -> The body of the function }
1
The outermost brace , If a parameter value is passed into the expression , You need to declare parameters , End of parameter list -> , Identify the end of the parameter list and the beginning of the function body , Arbitrary code can be written in the function body .
Now go back to the front , First maxBy The working principle of is to traverse according to the incoming conditions , So as to find the maximum value , therefore , To paraphrase Lambda The function expression can be written as :
val list1 = listOf("aa", "bbbb", "cc")
var lambda = { content :String -> content.length }
var maxLength = list1.maxBy ( lambda )
print(maxLength)
maxBy The function essentially receives a lambda Parameters ,
secondly , There is no need to specifically define a lambda Variable , You can directly lambda Expression passed in maxBy Function ,
val list1 = listOf("aa", "bbbb", "cc")
var maxLength = list1.maxBy( { content :String -> content.length })
print(maxLength)
stay Kotlin In the regulations , When Lambda When the parameter is the last parameter of a function , Can be Lambda Move the expression outside the parentheses ,
val list1 = listOf("aa", "bbbb", "cc")
var maxLength = list1.maxBy() { content :String -> content.length }
print(maxLength)
If Lambda Parameter is the only parameter of the function , Parentheses can be omitted ,
val list1 = listOf("aa", "bbbb", "cc")
var maxLength = list1.maxBy { content :String -> content.length }
print(maxLength)
because Kotlin Type derivation mechanism in ,Lambda Expressions do not have to declare parameter types in most cases ,
val list1 = listOf("aa", "bbbb", "cc")
var maxLength = list1.maxBy { content -> content.length }
print(maxLength)
Last , When Lambda When there is only one parameter in the parameter list of the expression , There is no need to declare the parameter name , You can use keywords directly it Instead of ,
val list1 = listOf("aa", "bbbb", "cc")
var maxLength = list1.maxBy { it.length }
print(maxLength)
5、 Commonly used set function API
(1)、map() function
It is used to map each element to another value , The mapping rule is Lambda The expression specifies , Finally, a new set is generated ,
val list1 = listOf("aa", "bb")
var newList = list1.map{ it.toUpperCase()}
for (content in list1){
content.toUpperCase() // Convert to uppercase mode
}
(2)、filter() function
Used to filter the data in the collection , Can be used alone , Can also be combined with map() Use it together
val list1 = listOf("aa", "bbbb", "cc")
var list2 = list1.filter { it.length <= 2 }
.map { it.toUpperCase() }
(3)、any() function
Judge whether at least one element in the set meets the specified conditions
val list1 = listOf("aa", "bbbb", "cc")
var anyResult = list1.any { it.length <= 2 }
(4)、all() function
Judge whether all elements in the set meet the specified conditions
val list1 = listOf("aa", "bbbb", "cc")
var allResult = list1.all { it.length <= 2 }边栏推荐
- If you can quickly generate a dictionary from two lists
- Basic data types in golang
- What are the advantages of automation?
- Solution to null JSON after serialization in golang
- C # use smtpclient The sendasync method fails to send mail, and always returns canceled
- Matlab tips (25) competitive neural network and SOM neural network
- Problems encountered by scan, scanf and scanln in golang
- 【leetcode】540. A single element in an ordered array
- Hands on deep learning (34) -- sequence model
- Golang Modules
猜你喜欢

How do microservices aggregate API documents? This wave of show~

How web pages interact with applets

Kubernetes CNI 插件之Fabric

C language pointer interview question - the second bullet

2022-2028 global optical transparency industry research and trend analysis report

Hands on deep learning (33) -- style transfer

QTreeView+自定义Model实现示例

Mmclassification annotation file generation

2022-2028 global elastic strain sensor industry research and trend analysis report

MATLAB小技巧(25)竞争神经网络与SOM神经网络
随机推荐
C # use smtpclient The sendasync method fails to send mail, and always returns canceled
How to batch change file extensions in win10
Hands on deep learning (35) -- text preprocessing (NLP)
MySQL transaction mvcc principle
Analysis report on the development status and investment planning of China's modular power supply industry Ⓠ 2022 ~ 2028
El Table Radio select and hide the select all box
2022-2028 global tensile strain sensor industry research and trend analysis report
Write a mobile date selector component by yourself
C # use gdi+ to add text with center rotation (arbitrary angle)
2022-2028 global strain gauge pressure sensor industry research and trend analysis report
Hands on deep learning (44) -- seq2seq principle and Implementation
PHP is used to add, modify and delete movie information, which is divided into foreground management and background management. Foreground users can browse information and post messages, and backgroun
Global and Chinese markets of hemoglobin analyzers in care points 2022-2028: Research Report on technology, participants, trends, market size and share
Golang defer
Get the source code in the mask with the help of shims
2022-2028 global optical transparency industry research and trend analysis report
C语言指针面试题——第二弹
pcl::fromROSMsg报警告Failed to find match for field ‘intensity‘.
xxl-job惊艳的设计,怎能叫人不爱
查看CSDN个人资源下载明细