Convert query string from map

If you are already working with a Groovy Map as a data structure, transforming it to a query string is straight forward as both naturally have name/value pair structure. Performing a quick search on google we pulled the query parameters creating a map. Next calling the collect will iterate through each entry in the map transforming with the closure passed. Finally, calling join will combine them separating each element with a & will combine all the elements with & (ampersand). Two things to be aware of, first is that the values aren't encoded and second is that it is possible to have multiple query parameters with the same name. Since Maps naturally don't support duplicate values you may need to look for alternative if your use case requires it. A comparable examples shows how to convert a Hashmap to query string using java.

@Test
void query_string_from_map() {

    def queryParamsAsMap = [
        "gws_rd": "ssl", "safe": "off", "q": "level+up+lunch"
    ]

    def queryString = queryParamsAsMap
                            .collect { k,v -> "$k=$v" }
                            .join('&')

    assert "gws_rd=ssl&safe=off&q=level+up+lunch" == queryString

}