Picocli: How to pass multiple values for same key to a Map?

Created on 21 Jan 2020  路  5Comments  路  Source: remkop/picocli

I would like to group values by key with a command

Here is what I tried:

@Option(names = {"-t"}, split = ",")
protected Map<String, List<Path>> resources;

with the command arguments: -t key=a/b/c.txt,a/b/c2.txt -t key2=d/e/f.txt -t key=a/b/c3.txt

This doesn't seem to be supported. I get java.lang.ClassCastException: java.lang.String cannot be cast to java.util.List at runtime, which indicated that picocli puts a String into the map as value even though it is of type List<String>.

question

All 5 comments

Hi!

Yes, the split attribute serves to separate map entries, it does not operate on the map values. For example:

@Option(names = {"-t"}, split = ",")
protected Map<String, Path> resources;

This would accept input like -t key=a/b/c.txt,key2=a/b/c2.txt,key3=d/e/f.txt.

But anyway, this is not what you want.
Picocli does not support Map<String, List<Path>> out of the box, but you may be able to achieve this with a custom parameter processor.

Here is an example: https://github.com/remkop/picocli/blob/master/picocli-examples/src/main/java/picocli/examples/optionaloptionparams/OptionalOptionParamDemo.java

@guw Did this answer your question?

@remkop I went with a List<String> and additional parsing within the application logic to get the data I want. I haven't tried the custom parameter processor but it looks like it would do it.

Makes sense.
I鈥檒l close this ticket, feel free to raise other ones at any time.

Please star picocli on GitHub if you like the project. :-)

Was this page helpful?
0 / 5 - 0 ratings