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.

JavaCli Tooling

Code

snippet
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

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 =`.