当前位置:网站首页>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 Hashtable

3、 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.red

4、 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

原网站

版权声明
本文为[Leisurely summer]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/174/202206231100545764.html

随机推荐