Groovy Convert List

I am having a problem in groovy trying to figure out how to convert a single item to a list. I have an input variable params.contactsthat can be a single value (e.g. 14) or can be an array of values ​​(e.g. 14, 15). I want to always turn it into a list. I used to just talk params.contacts.toList(), but this code fails when it is a single element. It takes 14 and splits it into a list [1, 4].

Is there a simple and elegant way to solve this problem?

+3
source share
1 answer

One easy way is to put it in a list and smooth it out:

def asList(orig) {
    return [orig].flatten()
}

assert [1, 2, 3, 4] == asList([1, 2, 3, 4])
assert ["foo"] == asList("foo")
assert [1] == asList(1)

, , , :

assert [[1, 2], [3, 4]] == asList([[1, 2], [3, 4]])  // fails!

- :

def asList(Collection orig) {
    return orig
}

def asList(orig) {
    return [orig]
}

assert [1, 2, 3, 4] == asList([1, 2, 3, 4])
assert ["foo"] == asList("foo")
assert [1] == asList(1)
assert [[1, 2], [3, 4]] == asList([[1, 2], [3, 4]])  // works!

. , . . Java - groovy, , .

+8

Source: https://habr.com/ru/post/1727180/


All Articles