当前位置:网站首页>Groovy map operation
Groovy map operation
2022-06-23 13:32:00 【Leisurely summer】
1、Map How to generate
Mode one :Java The way
def map = new HashMap() Mode two :Groovy The way
def colors = ['red': ' Red ', 'green': ' green ', blue: ' Blue '] // Keys can be without single quotes Be careful :map The key of must be specified as an immutable single quote string , If no single quotation mark is specified for the key , The compiler automatically adds ( That is, the key writes the value directly , No single quotation marks )
2、 change Groovy Default map type
map The default is LinkedHashMap, If we want to specify the collection type , Can be def Replace the keyword with what you want map type , for example
If I want to specify as Hashtable
HashMap colors = ['red': ' Red ', 'green': ' green ', 'blue': ' Blue ']Or use as keyword , Complete the assignment map type
def colors = ['red': ' Red ', 'green': ' green ', 'blue': ' Blue '] as Hashtable3、 Get collection elements
Mode one : Use getAt Method to get
colors.getAt("red")Mode two : Use variable names [“ key ”]
println colors['red']Mode three : Use variable names . Key name
colors.red4、 Additive elements
4.1、put Method
colors.put("yellow", " yellow ")4.2、 Variable name . Key name = value
colors.yellow = 'fff00' 4.3、leftShift Method
colors.leftShift([" Brown ": 'brown'])Be careful : What's coming in is a map aggregate
4.4、 Add nested elements
colors.complex = ["a": 3, "b": 5]notes : stay map To get class attributes from a collection, you must use getClass Method , They can't be used .class Method obtained
5、 Remove elements
Use remove Method , This method has two overloaded methods , The first overloaded method requires only one parameter , Is the key of the set ; The second overloaded method requires two parameters , Respectively key And value, Delete elements in the collection according to key value pairs
colors.remove("green")
6、Map Common operations
6.1、 Traverse
6.1.1、 Use each Method
Students.each {
def student ->
println "the key is ${student.key} and the value is ${student.value}"
}This method is based on Map In the collection Entry( Key value pair ) Traversal , Can also be based on key And value Traversal , It should be noted that ,key And value The order of parameters cannot be reversed , Otherwise, the data will be disordered
// Direct traversal key, value Instead of traversing entry
Students.each { key, value ->
println "the key is ${key} and , the value is ${value}"
}6.1.2、eachWithIndex Method
This is an indexed traversal
// Indexed each Traverse
Students.eachWithIndex { def student, int index -> // The order of the two cannot be reversed
println "the index is ${index} , the key is ${student.key} , and the value is ${student.value}"
}This method can also be used for pages key And value With index map A collection of traverse , Use eachWithIndex Method , But the same index Must be the last parameter , Otherwise, the data will be disordered
Students.eachWithIndex { def key, def value, int index -> // The order of the three cannot be reversed
println "the index is ${index} , the key is ${key} , and the value is ${value}"
}6.2、Map Search operation
6.2.1、find Method
This method uses closures to find the first element that meets the closure condition
def entry = Students.find { def student ->
return student.value.score >= 60
}6.2.2、findAlll Method
This method uses closures to find all the elements that meet the closure conditions
def entries = Students.findAll { def student ->
return student.value.score <= 60
}6.3、count Statistical methods
This method relies on closures , Count the number of elements that meet closure conditions , The return value is Integer
// count Statistical methods
def count = Students.count { def student ->
return student.value.score >= 60 && student.value.sex == 'male'
}
6.4、collect Method
Filter the set , A list of eligible elements is generated
// Query all students whose grades are greater than or equal to 60 Name
def names = Students.findAll { def student ->
return student.value.score >= 60
}.collect { return it.value.name } // Filter the set , A list of qualified student names is generated 6.5、groupBy Method
With the help of closures , According to the specified conditions Map Group sets
// Group according to the results
def group = Students.groupBy { def student ->
return student.value.score >= 60 ? ' pass ' : ' fail, '
}6.6、Map The sorting operation
Use sort Method , According to the conditions defined in the closure Map Set to sort
def sort = Students.sort { def student1, def student2 ->
Number score1 = student1.value.score
Number score2 = student2.value.score
return score1 == score2 ? 0 : score1 < score2 ? -1 : 1
}Be careful :list Of sort The sorting method has no return value , and map Medium sort The method returns a value , It's a new map aggregate
边栏推荐
- Can cold plate, submerged and spray liquid cooling lead the development of high-performance computing?
- 华三交换机配置SSH远程登录
- How to use androd gradle module dependency replacement
- Have you ever encountered incompatibility between flink1.15.0 and Flink CDC MySQL 2.2.1? f
- React query tutorial ④ - cache status and debugging tools
- DBMS in Oracle_ output. put_ How to use line
- 你管这破玩意儿叫 MQ?
- 怎么手写vite插件
- R语言使用nnet包的multinom函数构建无序多分类logistic回归模型、使用回归系数及其标准误计算每个系数对应的Z统计量的值、使用pnorm函数计算Z统计量对应的p值判断变量的显著性
- 美国的国家公园概览
猜你喜欢

你管这破玩意儿叫 MQ?

16 channel HD-SDI optical transceiver multi channel HD-SDI HD video optical transceiver 16 channel 3g-sdi HD audio video optical transceiver

Go写文件的权限 WriteFile(filename, data, 0644)?

C语言的基本数据类型及其打印输出

在線文本過濾小於指定長度工具

windows 安装 MySQL

Hanyuan hi tech 8-way telephone +1-way 100M Ethernet RJ11 telephone optical transceiver 8-way PCM telephone optical transceiver

【网站架构】10年数据库设计浓缩的绝技,实打实的设计步骤与规范

First exposure! The only Alibaba cloud native security panorama behind the highest level in the whole domain

2 万字 + 30 张图 |MySQL 日志:undo log、redo log、binlog 有什么用?
随机推荐
R language dplyr package arrange function sorts dataframe data and sorts dataframe data through multiple data columns (ascending sort by default)
【网站架构】10年数据库设计浓缩的绝技,实打实的设计步骤与规范
Hanyuan hi tech 1-way uncompressed 4k-dvi optical transceiver 4K HD uncompressed DVI to optical fiber 4k-dvi HD video optical transceiver
理财产品长期是几年?新手最好买长期还是短期?
2022软科大学专业排名出炉!西电AI专业排名超清北,南大蝉联全国第一 !
618的省钱技术攻略 来啦 -体验场景 领取10元猫超卡!
Germancreditdata of dataset: a detailed introduction to the introduction, download and use of germancreditdata dataset
16 channel HD-SDI optical transceiver multi channel HD-SDI HD video optical transceiver 16 channel 3g-sdi HD audio video optical transceiver
Quickly understand the commonly used asymmetric encryption algorithm, and no longer have to worry about the interviewer's thorough inquiry
sed -i命令怎么使用
The GLM function of R language uses frequency data to build a binary logistic regression model. The input data for analysis is frequency data, which is transformed into normal sample data (split and s
何小鹏:如果可以回到创业的时候 不会以自己的名字给产品命名
R language dplyr package mutate_ The all function multiplies all numeric columns (variables) in the dataframe by a fixed value to generate a new data column, and specifies a user-defined suffix name f
Gary Marcus wrote: three perspectives from linguists that AI researchers need to know
Stick to five things to get you out of your confusion!
R语言使用MASS包的polr函数构建有序多分类logistic回归模型、使用exp函数和coef函数获取模型中每个变量(自变量改变一个单位)对应的优势比(odds ratio)
Esp32-c3 introductory tutorial problem ⑦ - fatal error: ESP_ Bt.h: no such file or directory ESP not found_ bt.h
R language uses the polR function of mass package to build an ordered multi classification logistic regression model, and uses the summary function to obtain the summary statistical information of the
Service stability governance
【深入理解TcaplusDB技术】单据受理之事务执行