I’m trying to refactor someone else’s Groovy code, and it has a Collections.sort()
algorithm that I don’t understand. I’ve looked at Collections.sort() in Java with Examples (Java I know, but I Groovy is related, and can use Java libraries).
List json = new ArrayList()
def map = new HashMap()
def title = "Microservice1"
def uri = "https://someUrl.com/microservice1/api-docs"
map.put("name", title)
map.put("uri", uri)
json.push(map)
title = "Microservice2"
uri = "https://someUrl.com/microservice2/api-docs"
map.put("name", title)
map.put("url", uri)
json.push(map)
def api1 = "https://someApi1.com/api-docs"
def api2 = "https://someApi2.com/api-docs"
map = new HashMap()
map.put("name", "API 1")
map.put("url", api1)
json.push(map)
map = new HashMap()
map.put("name", "API 2")
map.put("url", api2)
json.push(map)
map = new HashMap()
map.put("name", "Leads")
map.put("url", api2 + "?groups=Leads")
json.push(map)
// What exactly does this do?
Collections.sort(json, new Comparator<Map<String, String>>() {
public int compare(Map<String, String> m1, Map<String, String> m2) {
return m1.get("name").compareTo(m2.get("name"));
}
});
I at least understand the Collections.sort()
can accept 2 parameters, the first one being the collection to be sorted, which is the json
variable in my case, and the second (optional) parameter is the sorting algorithm, which in this case is a Comparator
object whose constructor is the compare()
function? However, I don’t understand how maps m1
and m2
are instantiated, and hence what values they have? Can someone please explain? Thanks!