Java 17: Parse a log section with the Java 9 to 17 Stream and String APIs. Compare loops, Java 8 streams and modern streams.
Problem
From a log text, ignore everything before the BEGIN line and after the END line; between them, count ERROR lines, list the distinct error codes (E\d+), and report the minimum and maximum latency (latency=123ms).
class LogInput {
static final String TEXT = """
boot sequence
BEGIN
INFO GET /orders latency=120ms
ERROR E42 payment timeout latency=900ms
INFO GET /cart latency=80ms
ERROR E17 db pool exhausted latency=1500ms
ERROR E42 payment timeout latency=950ms
END
INFO shutdown latency=5ms
""";
}Approach 1: Plain loop with a state flag (works everywhere)
import java.util.Set;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class LogLoop {
static final Pattern CODE = Pattern.compile("\\bE\\d+\\b"), LATENCY = Pattern.compile("latency=(\\d+)ms");
static String analyse(String text) {
boolean inside = false;
int errors = 0;
long min = Long.MAX_VALUE, max = Long.MIN_VALUE;
Set<String> codes = new TreeSet<>();
for (String line : text.split("\n")) {
String l = line.trim();
if (l.equals("BEGIN")) { inside = true; continue; }
if (l.equals("END")) break;
if (!inside || l.isEmpty()) continue;
if (l.startsWith("ERROR")) {
errors++;
Matcher m = CODE.matcher(l);
if (m.find()) codes.add(m.group());
}
Matcher lat = LATENCY.matcher(l);
if (lat.find()) { long v = Long.parseLong(lat.group(1)); min = Math.min(min, v); max = Math.max(max, v); }
}
return "errors=" + errors + " codes=" + codes + " latency=" + min + ".." + max;
}
}Approach 2: Java 8 streams (awkward: no way to start or stop at a marker)
Java 8 streams lack dropWhile/takeWhile, so people reach for a mutable flag inside filter. It works sequentially but is a side-effecting lambda, which is fragile and wrong in parallel.
import java.util.Arrays;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
class LogJava8 {
static long errorCount(String text) {
AtomicBoolean inside = new AtomicBoolean(false), done = new AtomicBoolean(false);
return Arrays.stream(text.split("\n")).map(String::trim)
.filter(l -> { // stateful filter: anti-pattern
if (l.equals("END")) done.set(true);
if (done.get()) return false;
if (l.equals("BEGIN")) { inside.set(true); return false; }
return inside.get();
})
.filter(l -> l.startsWith("ERROR"))
.collect(Collectors.counting());
}
}Approach 3: Modern streams (Java 9 to 17)
String.lines()(Java 11) streams lines lazily;strip()andisBlank()(Java 11) are Unicode-aware.dropWhile/takeWhile(Java 9) express "skip until BEGIN, stop at END" without state.Stream.toList()(Java 16) returns an unmodifiable list.Collectors.teeing(Java 12) computes two aggregates in one pass.mapMulti(Java 16) emits zero or more values per element without creating streams.
import java.util.List;
import java.util.LongSummaryStatistics;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.stream.Collector;
import java.util.stream.Collectors;
class LogModern {
static String analyse(String text) {
List<String> section = text.lines()
.map(String::strip)
.dropWhile(l -> !l.equals("BEGIN")).skip(1) // skip up to and including BEGIN
.takeWhile(l -> !l.equals("END"))
.filter(l -> !l.isBlank())
.toList();
// teeing: error count and distinct codes from the same pass
Collector<String, ?, TreeSet<String>> distinctCodes =
Collectors.mapping(l -> l.split("\\s+")[1], Collectors.toCollection(TreeSet::new));
String errors = section.stream().filter(l -> l.startsWith("ERROR"))
.collect(Collectors.teeing(Collectors.counting(), distinctCodes,
(count, codes) -> "errors=" + count + " codes=" + codes));
// mapMulti: emit a latency only when the line has one
LongSummaryStatistics latency = section.stream()
.<Long>mapMulti((line, sink) -> {
Matcher m = LogLoop.LATENCY.matcher(line);
if (m.find()) sink.accept(Long.parseLong(m.group(1)));
})
.mapToLong(Long::longValue).summaryStatistics();
return errors + " latency=" + latency.getMin() + ".." + latency.getMax();
}
public static void main(String[] args) {
System.out.println(LogLoop.analyse(LogInput.TEXT)); // errors=3 codes=[E17, E42] latency=80..1500
System.out.println(LogJava8.errorCount(LogInput.TEXT)); // 3
System.out.println(LogModern.analyse(LogInput.TEXT)); // errors=3 codes=[E17, E42] latency=80..1500
}
}Feasible → optimal
All are O(lines). The loop is fastest and fine; Java 8 streams need a stateful hack; the modern stream version is declarative and side-effect free. For very large files use Files.lines(path) (lazy) with the same pipeline, so memory stays constant.
Follow-up questions interviewers ask
Try answering each one before you open it.
What is the difference between takeWhile and filter?
filter checks every element and keeps those that match. takeWhile stops at the first element that fails the predicate and ignores everything after it, so it can short-circuit an infinite stream (Stream.iterate(1, x -> x * 2).takeWhile(x -> x < 1000)). On unordered streams its result is not deterministic.
Why does `strip()` exist when there is `trim()`?
trim() removes characters with code point ≤ U+0020 (ASCII control characters and space). strip() uses Character.isWhitespace, so it also removes Unicode spaces such as U+2003 (em space) common in copied text. stripLeading() and stripTrailing() handle one side.