public static Map < String , Object > parseOptions ( List < String > args , OptArg ... options ) { HashMap < String , Object > result = new HashMap <> ( ) ; HashMap < String , OptArg > optmap = new HashMap <> ( ) ; for ( OptArg opt : options ) { if ( opt . defaultValue != null ) { result . put ( opt . option , opt . defaultValue ) ; } optmap . put ( opt . option , opt ) ; optmap . put ( opt . shortForm , opt ) ; } Iterator < String > iter = args . iterator ( ) ; while ( iter . hasNext ( ) ) { String arg = iter . next ( ) ; if ( arg . startsWith ( "-" ) ) { arg = arg . substring ( 1 , arg . length ( ) ) ; OptArg opt = optmap . get ( arg ) ; if ( opt != null ) { // matched iter . remove ( ) ; // remove option from args list Kind k = opt . argument ; if ( k != null ) { String param = iter . next ( ) ; iter . remove ( ) ; k . process ( opt . option , param , result ) ; } else { result . put ( opt . option , null ) ; } } else { throw new RuntimeException ( "unknown command-line option: -" + arg ) ; } } } return result ; }
Parse options from the list of arguments removing those which are recognised . Anything which is not recognised is left as is .