text parsing
data structure
mapping
programming
coding tips

Is there a simple way of parsing this text into a Map

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

Yes, if the text really follows a simple key-value structure. The hard part is usually not splitting strings. It is deciding the parsing rules up front so blank lines, comments, duplicate keys, and malformed entries are handled predictably instead of only on happy-path input.

Define the Input Contract First

Before writing parsing code, decide what each line means. A simple line-based format often uses rules like these:

  • one key-value pair per line
  • the first = separates key from value
  • blank lines are ignored
  • lines starting with # are comments
  • duplicate keys either overwrite or raise an error

Without those rules, the parser is just guessing.

A Small Java Parser

The following parser reads key=value text, ignores blank lines and comments, and records malformed lines separately from the parsed map.

java
1import java.util.ArrayList;
2import java.util.LinkedHashMap;
3import java.util.List;
4import java.util.Map;
5
6public class KeyValueParser {
7    public static class Result {
8        public final Map<String, String> map;
9        public final List<String> errors;
10
11        public Result(Map<String, String> map, List<String> errors) {
12            this.map = map;
13            this.errors = errors;
14        }
15    }
16
17    public static Result parse(String text) {
18        Map<String, String> out = new LinkedHashMap<>();
19        List<String> errors = new ArrayList<>();
20
21        String[] lines = text.split("\\R");
22        for (int i = 0; i < lines.length; i++) {
23            String raw = lines[i].trim();
24            if (raw.isEmpty() || raw.startsWith("#")) {
25                continue;
26            }
27
28            int idx = raw.indexOf('=');
29            if (idx <= 0) {
30                errors.add("line " + (i + 1) + " malformed: " + raw);
31                continue;
32            }
33
34            String key = raw.substring(0, idx).trim();
35            String value = raw.substring(idx + 1).trim();
36            out.put(key, value);
37        }
38
39        return new Result(out, errors);
40    }
41}

This keeps syntax parsing simple while still giving the caller enough information to react to bad lines.

Split on the First Delimiter Only

One of the easiest bugs is splitting on every = instead of only the first one. Values sometimes contain the delimiter themselves.

text
connection=Server=db;Mode=ReadWrite

The key should be connection, and everything after the first delimiter should remain in the value. That is why indexOf plus substring is often better than a naive split("=").

Example Usage

java
1public class Demo {
2    public static void main(String[] args) {
3        String text = """
4                # application settings
5                host = db.local
6                port = 5432
7                mode = read-write
8                broken_line
9                """;
10
11        KeyValueParser.Result result = KeyValueParser.parse(text);
12
13        System.out.println(result.map);
14        System.out.println(result.errors);
15    }
16}

This separation between parsed values and parse errors is often more useful than throwing immediately, because different callers may want different error-handling policies.

Decide How to Handle Duplicate Keys

Duplicate keys are common in hand-edited files, so you should choose a policy intentionally.

Common choices are:

  • last value wins
  • first value wins
  • duplicates are errors

The example parser uses “last value wins” because Map.put overwrites the old value. That is fine for override-style configuration, but if ambiguity is dangerous in your domain, you should detect duplicates and reject them.

Know When the Format Is No Longer Simple

A tiny custom parser is fine for a tiny format. It stops being fine when the text starts needing:

  • quoting
  • escaping
  • nested data
  • arrays
  • multiline values

At that point, a standard format such as JSON, YAML, or TOML is usually safer than extending an ad hoc parser indefinitely.

Common Pitfalls

The most common mistake is writing parsing code before defining what counts as a valid line.

Another pitfall is splitting on every delimiter and corrupting values that legitimately contain =. Developers also often mix syntax parsing and business validation into one step, which makes the code harder to debug and evolve.

Finally, do not assume trim() is always correct for every format. Some input formats treat leading or trailing spaces inside values as meaningful.

Summary

  • Parsing text into a Map is straightforward when the input contract is explicit.
  • Handle blanks, comments, malformed lines, and duplicates deliberately.
  • Split on the first delimiter only.
  • Keep syntax parsing separate from business validation.
  • Move to a standard structured format once the text stops being truly simple.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.