Parse CLI Options Into Map And Positional Args
Hand-roll a minimal CLI parser: --key=value options land in a map, bare switches become true, and leftover arguments stay positional.
Code
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class CliArgs {
record Parsed(Map<String, String> options, List<String> positional) {}
// minimal CLI convention: --key=value switches, bare flags, positional args
static Parsed parse(String[] args) {
Map<String, String> options = new LinkedHashMap<>();
List<String> positional = new ArrayList<>();
for (String arg : args) {
if (arg.startsWith("--")) {
int eq = arg.indexOf('=');
if (eq < 0) {
options.put(arg.substring(2), "true"); // bare switch
} else {
options.put(arg.substring(2, eq), arg.substring(eq + 1));
}
} else {
positional.add(arg);
}
}
return new Parsed(options, positional);
}
public static void main(String[] args) {
String[] sample = {"--port=8443", "--verbose", "app.log", "db.log"};
Parsed parsed = parse(sample);
System.out.println("port = " + parsed.options().getOrDefault("port", "8080"));
System.out.println("verbose = " + parsed.options().getOrDefault("verbose", "false"));
System.out.println("files = " + parsed.positional());
}
}Inside the snippet
The snippet is organized around the classes CliArgs and Parsed and the functions parse and main.
A single loop drives the file — for (String arg : args).
What to watch for
- Self-sufficient by design — there is no registry and no lockfile entry.
Using it
The main signature reads static Parsed parse(String[] args)
Each run prints the 3 labeled blocks port =, verbose =, files = in source order.
Launch the file; main takes over and steps through parse.
Key statements
return new Parsed(options, positional);
Interactive Tools for This Topic
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- What does Parse CLI Options Into Map And Positional Args print when run?
- The script runs standalone; its 3 labeled outputs include `port =`, `verbose =`, `files =`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.