Matthias
Matthias

Reputation: 10379

Groovy's "in" operator for lists with String and GString elements

The following piece of Groovy code prints an empty list:

List<String> list = ["test-${1+2}", "test-${2+3}", "test-${3+4}"]
List<String> subl = ["test-1", "test-2", "test-3"]
println subl.findAll { it in list }

Output:

[]

However, this modification leads to the correct output:

List<String> list = ["test-${1+2}" as String, "test-${2+3}" as String, "test-${3+4}" as String]
List<String> subl = ["test-1", "test-2", "test-3"]
println subl.findAll { it in list }

Output:

[test-3]

But this "solution" feels very clunky.
What is the correct Groovy way to achieve this?

Upvotes: 4

Views: 1451

Answers (1)

cfrick
cfrick

Reputation: 37008

You can use the *. spread operator to get Strings easily (see list2 example below). But your check there can be done alot easier with intersect.

List<String> list = ["test-${1+2}", "test-${2+3}", "test-${3+4}"]
List<String> subl = ["test-1", "test-2", "test-3"]
assert subl.findAll{ it in list }==[] // wrong

// use intersect for a shorter version, which uses equals
assert subl.intersect(list)==['test-3']

// or with sets...
assert subl.toSet().intersect(list.toSet())==['test-3'].toSet()

// spread to `toString()` on your search
List<String> list2 = ["test-${1+2}", "test-${2+3}", "test-${3+4}"]*.toString()
assert subl.findAll{ it in list2 }==['test-3']

Upvotes: 3

Related Questions