Thursday, 24 January 2019

Groovy : List: max: Find maximum element in the list


Groovy provides max() method that returns the maximum element in the list. ‘max’ method available in below overloaded forms.

public Object max()
public Object max(Closure closure)
public Object max(Comparator comparator)

public Object max()
Return the maximum value in the list.

HelloWorld.groovy
numbers = [1, 100, 98, 32, 456, 78, 90]
cities = ["Bangalore", "New Delhi", "Calcutta", "Chennai", "Amaravathi"]

println "numbers.max() : ${numbers.max()}"
println "cities.max() : ${cities.max()}"

Output
numbers.max() : 456
cities.max() : New Delhi

public Object max(Closure closure)
Return the maximum value based on closure (Closure is used to determine ordering). Closure can be 1 or 2-order closure.


HelloWorld.groovy
cities = ["Bangalore", "New Delhi", "Calcutta", "Chennai", "Amaravathi"]

longestCityName = cities.max{it.length()}
cityNameByName = cities.max{a, b -> a.compareTo(b)}

println "longestCityName : $longestCityName"
println "cityNameByName : $cityNameByName"

Output
longestCityName : Amaravathi
cityNameByName : New Delhi

public Object max(Comparator comparator)
Selects the maximum value found in the Iterable using the given comparator.


HelloWorld.groovy
cities = ["Bangalore", "New Delhi", "Calcutta", "Chennai", "Amaravathi"]

Comparator nameComparator = { a, b -> a.compareTo(b) } 
Comparator lengthComparator = {a, b -> a.length()-b.length()}

cityNameByName = cities.max(nameComparator)
cityNameByLength = cities.max(lengthComparator)

println "cityNameByName : $cityNameByName"
println "cityNameByLength : $cityNameByLength"

Output
cityNameByName : New Delhi
cityNameByLength : Amaravathi



Previous                                                 Next                                                 Home

No comments:

Post a Comment