java
42 lines · 6 steps
Counting HTTP statuses with Java streams
Stream a log file line by line, pull out HTTP status codes with a regex, and tally them without loading everything into memory.
Explained by
highlit
1package com.example.logs;
2
3import java.io.IOException;
4import java.io.UncheckedIOException;
5import java.nio.charset.StandardCharsets;
6import java.nio.file.Files;
7import java.nio.file.Path;
8import java.util.Map;
9import java.util.regex.Matcher;
10import java.util.regex.Pattern;
11import java.util.stream.Collectors;
12import java.util.stream.Stream;
13
14public final class AccessLogAnalyzer {
15
16 private static final Pattern STATUS = Pattern.compile("\"\\s(\\d{3})\\s");
17
18 public Map<Integer, Long> countByStatus(Path logFile) throws IOException {
19 try (Stream<String> lines = Files.lines(logFile, StandardCharsets.UTF_8)) {
20 return lines
21 .map(STATUS::matcher)
22 .filter(Matcher::find)
23 .map(m -> Integer.parseInt(m.group(1)))
24 .collect(Collectors.groupingBy(
25 status -> status,
26 Collectors.counting()));
27 }
28 }
29
30 public long countServerErrors(Path logFile) {
31 try (Stream<String> lines = Files.lines(logFile, StandardCharsets.UTF_8)) {
32 return lines
33 .map(STATUS::matcher)
34 .filter(Matcher::find)
35 .map(m -> Integer.parseInt(m.group(1)))
36 .filter(status -> status >= 500)
37 .count();
38 } catch (IOException e) {
39 throw new UncheckedIOException("Failed to read " + logFile, e);
40 }
41 }
42}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Files.lines returns a lazy stream that must be closed, so wrapping it in try-with-resources frees the file handle even on a partial read.
- 2Collectors.groupingBy paired with counting turns a stream of values into a frequency map in one pass.
- 3Wrapping a checked IOException in UncheckedIOException lets a method stay clean while still surfacing failures.
Related explainers
java
public interface GitHubClient { @GetExchange("/users/{username}") GitHubUser getUser(@PathVariable String username);
Declarative HTTP clients in Spring
http-client
declarative-api
proxy
Intermediate
8 steps
ruby
class TemplateInterpolator PLACEHOLDER = /\{\{\s*([\w.]+)\s*\}\}/ def initialize(strict: false)
Interpolating templates with dotted keys in Ruby
regex
string-interpolation
hash-traversal
Intermediate
6 steps
java
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;
Building a trie for autocomplete in Java
trie
prefix-tree
recursion
Intermediate
8 steps
java
@RestController @RequestMapping("/api/products") public class ProductSearchController {
Binding collection query params in Spring
rest-api
query-parameters
dependency-injection
Intermediate
6 steps
java
import java.util.ArrayDeque; import java.util.Deque; import java.util.Map;
Evaluating math expressions with two stacks
stacks
parsing
operator-precedence
Intermediate
9 steps
java
@Entity @Table(name = "orders") @SQLDelete(sql = "UPDATE orders SET deleted = true, deleted_at = now() WHERE id = ?") @Where(clause = "deleted = false")
Soft deletes with Hibernate in Spring
soft-delete
jpa
hibernate
Intermediate
9 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/counting-http-statuses-with-java-streams-explained-java-5964/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.