Reputation: 26549
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;
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) {
What is the most concise way of entering String Arrays
into a map??
I don't like 2. Current Solution
.
Upvotes: 1
Views: 1523
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
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
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