Multi-stream: order merged alerts by severity then time

Two monitoring feeds, one queue for the on-call engineer. Comparator.comparingInt().thenComparingInt() gives the ranking rule; without the tie-break the order inside a severity band depends on which feed was concatenated first.

Code
record Alert(String source, int severity, int at, String msg) {}

var infra = List.of(new Alert("infra", 2, 10, "disk 80%"), new Alert("infra", 1, 30, "node down"));
var app = List.of(new Alert("app", 1, 20, "5xx spike"), new Alert("app", 3, 5, "slow query"));

Stream.concat(infra.stream(), app.stream())
      .sorted(Comparator.comparingInt(Alert::severity).thenComparingInt(Alert::at))
      .forEach(a -> System.out.println("P" + a.severity() + " " + a.at() + "s [" + a.source() + "] " + a.msg()));
Output
P1 20s [app] 5xx spike
P1 30s [infra] node down
P2 10s [infra] disk 80%
P3 5s [app] slow query
Advertisement
More in JAVA

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-09-20

© Java Coding Hub · About · Contact · Privacy · Terms