当前位置:网站首页>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 }
边栏推荐
- Write a jison parser from scratch (3/10): a good beginning is half the success -- "politics" (Aristotle)
- 2022-2028 research and trend analysis report on the global edible essence industry
- 查看CSDN个人资源下载明细
- [on February 11, 2022, the latest and most fully available script library collection of the whole network, a total of 23]
- 法向量点云旋转
- 品牌连锁店5G/4G无线组网方案
- Global and Chinese market of bipolar generators 2022-2028: Research Report on technology, participants, trends, market size and share
- 2022-2028 global industrial gasket plate heat exchanger industry research and trend analysis report
- C # use smtpclient The sendasync method fails to send mail, and always returns canceled
- Tkinter Huarong Road 4x4 tutorial II
猜你喜欢
ASP. Net to access directory files outside the project website
xxl-job惊艳的设计,怎能叫人不爱
直方图均衡化
libmysqlclient.so.20: cannot open shared object file: No such file or directory
pcl::fromROSMsg报警告Failed to find match for field ‘intensity‘.
Mmclassification annotation file generation
PHP book borrowing management system, with complete functions, supports user foreground management and background management, and supports the latest version of PHP 7 x. Database mysql
PHP student achievement management system, the database uses mysql, including source code and database SQL files, with the login management function of students and teachers
el-table单选并隐藏全选框
Log cannot be recorded after log4net is deployed to the server
随机推荐
2022-2028 global gasket metal plate heat exchanger industry research and trend analysis report
Problems encountered by scan, scanf and scanln in golang
C # use gdi+ to add text with center rotation (arbitrary angle)
Are there any principal guaranteed financial products in 2022?
Development trend and market demand analysis report of high purity tin chloride in the world and China Ⓔ 2022 ~ 2027
Write a jison parser from scratch (4/10): detailed explanation of the syntax format of the jison parser generator
Trees and graphs (traversal)
【leetcode】540. A single element in an ordered array
MySQL foundation 02 - installing MySQL in non docker version
Hands on deep learning (42) -- bi-directional recurrent neural network (BI RNN)
2022-2028 global strain gauge pressure sensor industry research and trend analysis report
Kotlin:集合使用
PMP registration process and precautions
Global and Chinese market of wheel hubs 2022-2028: Research Report on technology, participants, trends, market size and share
pcl::fromROSMsg报警告Failed to find match for field ‘intensity‘.
If you can quickly generate a dictionary from two lists
2022-2028 global industry research and trend analysis report on anterior segment and fundus OTC detectors
Write a jison parser from scratch (5/10): a brief introduction to the working principle of jison parser syntax
回复评论的sql
Summary of reasons for web side automation test failure