1

I have following arguments to add to CLI
-sbx
-CSWConfig
-stripInfo
-modelSources
-catchArchive
-swSupplierName
-modelsSWExchnage

but while displaying help it is showing these options in sorted order(as shown below) which I dont want, I want all the options to be in order as they are added.
-CatchArchive
-CSWConfig
-modelSources
-sbx
-stripInfo
-swSupplierName

I read one link for this but I am not able to preserve the ordering while displaying help contents.

private void print_help() {
    String CONST_STR_CLI_INFO = "ercli.exe custzip";
    HelpFormatter formatter = new HelpFormatter();
    formatter.setOptionComparator(new Comparator() {

        @Override
        public int compare(Object o1, Object o2) {
            Option op1=(Option) o1;
            Option op2=(Option) o2;
            return //what to do here?
        }
    });
    formatter.printHelp(CONST_STR_CLI_INFO, null, options, "", true);
}
Community
  • 1
  • 1
user3462473
  • 349
  • 4
  • 14
  • In [link](http://stackoverflow.com/questions/11741625/apache-commons-cli-ordering-help-options/12449193#12449193) 4th answer has given return opt1.getKey().compareToIgnoreCase(opt2.getKey()); You will get that. – Sushant Tambare Oct 08 '14 at 12:39

1 Answers1

0

As the Options() class stores the options in Maps internally, it does not keep any ordering. That means you need to provide your own order as you already found out.

To get the ordering, you can put the keys in a List upfront to have an index of required order for each element:

final List<String> optionKeys = new ArrayList<>();

optionKeys.add("sbx");
optionKeys.add("CSWConfig");
optionKeys.add("stripInfo");
optionKeys.add("modelSources");
optionKeys.add("catchArchive");
optionKeys.add("swSupplierName");
optionKeys.add("modelsSWExchnage");

Then in the Comparator you can compare by index in this list:

    @Override
    public int compare(Object o1, Object o2) {
        Option op1=(Option) o1;
        Option op2=(Option) o2;
        return Integer.compare(optionKeys.indexOf(op1.getLongOpt()), optionKeys.indexOf(op1.getLongOpt()));
    }
centic
  • 15,565
  • 9
  • 68
  • 125
  • thanks for help, but how we will get key in this statement optionKeys.indexOf(o1.key), I am getting error for "o1.key" – user3462473 Oct 09 '14 at 07:45
  • @centic I also have similar question [here](http://stackoverflow.com/questions/27614571/how-to-use-apache-commons-cli-to-parse-the-property-file-and-help-option) which uses Apache Commons CLI. If possible, can you help me out there? – john Dec 23 '14 at 05:53