LearnFrenzy
Sign in Take a free test

Streams API · Streams API Programs · Question 4

Web server log analysis with streams in Java Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 4 Back to Exercise

Parse access-log lines "method path status ms", then report the error rate, the slowest request, the average response time per status class (2xx/4xx/5xx) and the most requested path.

Solution
Main.java
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

record Hit(String method, String path, int status, int ms) {
    static Hit parse(String line) {
        String[] p = line.trim().split("\\s+");
        return new Hit(p[0], p[1], Integer.parseInt(p[2]), Integer.parseInt(p[3]));
    }
}

public class Main {
    public static void main(String[] args) {
        String log = """
            GET /home 200 120
            GET /products 200 340
            POST /login 401 80
            GET /products 200 290
            GET /cart 500 1500
            GET /home 200 95
            POST /checkout 503 2100
            GET /products 404 60
            """;
        List<Hit> hits = log.lines().filter(l -> !l.isBlank()).map(Hit::parse).toList();

        long errors = hits.stream().filter(h -> h.status() >= 400).count();
        System.out.printf("%d requests, error rate %.1f%%%n", hits.size(), errors * 100.0 / hits.size());
        System.out.println("slowest: " + hits.stream().max(Comparator.comparingInt(Hit::ms)).map(h -> h.path() + " " + h.ms() + "ms").orElse("-"));

        Map<String, Double> avgByClass = hits.stream().collect(Collectors.groupingBy(h -> h.status() / 100 + "xx", TreeMap::new, Collectors.averagingInt(Hit::ms)));
        System.out.println("avg ms " + avgByClass);

        String popular = hits.stream().collect(Collectors.groupingBy(Hit::path, Collectors.counting()))
            .entrySet().stream().max(Map.Entry.comparingByValue()).map(Map.Entry::getKey).orElse("-");
        System.out.println("most requested: " + popular);
    }
}

Output Verified by compiling and running

8 requests, error rate 50.0%
slowest: /checkout 2100ms
avg ms {2xx=211.25, 4xx=70.0, 5xx=1800.0}
most requested: /products

String.lines() turns text into a stream of lines; mapping each to a record makes the later queries readable.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links