Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you declare and use a Set data structure in groovysh?

I've tried:

groovy:000> Set<String> s = ["a", "b", "c", "c"]
===> [a, b, c]
groovy:000> s
Unknown property: s

I want to be able to use this as a set, but even if I pass it explicitly, it turns it into an ArrayList:

groovy:000> joinList(["a", "b", "c", "c"])
ERROR groovy.lang.MissingMethodException:
No signature of method: groovysh_evaluate.joinList() is applicable for argument types: (java.util.ArrayList) values: [[a, b, c, c]]
Possible solutions: joinList(java.util.Set)
like image 771
reectrix Avatar asked Jan 08 '15 19:01

reectrix


People also ask

What is set in Groovy?

Set. grep() Iterates over the collection returning each element that matches using the IDENTITY Closure as a filter - effectively returning all elements which satisfy Groovy truth.

How do you set a variable in Groovy?

Variables in Groovy can be defined in two ways − using the native syntax for the data type or the next is by using the def keyword. For variable definitions it is mandatory to either provide a type name explicitly or to use "def" in replacement. This is required by the Groovy parser.

How do you write a method in Groovy?

A method is in Groovy is defined with a return type or with the def keyword. Methods can receive any number of arguments. It's not necessary that the types are explicitly defined when defining the arguments. Modifiers such as public, private and protected can be added.

What are the data types in Groovy?

Groovy supports the same primitive types as defined by the Java Language Specification: integral types: byte (8 bit), short (16 bit), int (32 bit) and long (64 bit) floating-point types: float (32 bit) and double (64 bit) the boolean type (one of true or false )


1 Answers

This problem only occurs because you're using the Groovy Shell to test your code. I don't use the Groovy shell much, but it seems to ignore types, such that

Set<String> s = ["a", "b", "c", "c"]

is equivalent to

def s = ["a", "b", "c", "c"]

and the latter does of course create a List. If you run the same code in the Groovy console instead, you'll see that it does actually create a Set

Set<String> s = ["a", "b", "c", "c"]
assert s instanceof Set

Other ways to create a Set in Groovy include

["a", "b", "c", "c"].toSet()

or

["a", "b", "c", "c"] as Set
like image 85
Dónal Avatar answered Sep 19 '22 20:09

Dónal