Menelaos
Menelaos

Reputation: 26549

Groovy - Initializing String[] on the fly

1.Intro

I have a method that takes a String[] within a Map. I am generating this map within a unit test.

        Map<String, String[]> queryParameters = new HashMap<>();
        queryParameters.put("keywords",["keywords"].toArray()  )
        queryParameters.put("user", ["m"].toArray() )
        queryParameters.put("type", ["type"].toArray() )

Unfortunately toArray() produces an Array of Objects so it throws an exception:

java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;

2.Current Solution

I would like to avoid having to initialize the String arrays as:

String[] keywords = ["keywords"];
queryParameters.put("keywords",keywords)

This works but it's annoying. Also I don't want to change the original Spring/Java method definition which is:

 public Page<LoggingEvent> findAll(Pageable pageable, Map<String, String[]> parameters) {

3.Question

What is the most concise way of entering String Arrays into a map??

I don't like 2. Current Solution.

Upvotes: 1

Views: 1523

Answers (3)

ChrisGeo
ChrisGeo

Reputation: 3917

Try this

def parameters = [
        keywords: ["keywords"],
        users: ["m"],
        type: ["type"]
    ].collectEntries {[(it.key): it.value as String[]] } as HashMap<String, String[]>

Alternatively you could also do:

 def parameters = [
         keywords: ["keywords"] as String[],
         users: ["m"] as String[],
         type: ["type"] as String[]
     ]

Upvotes: 1

J&#233;r&#233;mie B
J&#233;r&#233;mie B

Reputation: 11032

You can use metaprogramming in order to help your script :

Map.metaClass.asStringArrayMap = {
  delegate.collectEntries { key, value -> [(key): value as String[]] }
}

[keyword:'keywords', user:'m', type:'type'].asStringArrayMap()

Upvotes: 2

Bhushan
Bhushan

Reputation: 567

You can initialize array in inline as follow

Map<String, String[]> queryParameters = new HashMap<>();
queryParameters.put("keywords",new String[]{"keyword"});
queryParameters.put("user", new String[]{"m"});
queryParameters.put("type", new String[]{"type"});

Upvotes: -1

Related Questions