Multi-stream: last-write-wins per key across two status feeds

Two systems report the same order and you want the newest state. toMap's merge function is the tie-break, and it compares event time rather than arrival order - which is the whole point, because arrival order lies.

Code
record Status(String orderRef, int at, String state) {}

var feedA = List.of(new Status("A-1", 1, "NEW"), new Status("A-2", 2, "NEW"));
var feedB = List.of(new Status("A-1", 9, "SHIPPED"), new Status("A-1", 5, "PAID"),
                    new Status("A-2", 4, "PAID"));

Map<String, Status> latest = Stream.concat(feedA.stream(), feedB.stream())
        .collect(Collectors.toMap(Status::orderRef, s -> s,
                                  (x, y) -> x.at() >= y.at() ? x : y,
                                  TreeMap::new));

latest.forEach((ref, s) -> System.out.println(ref + " " + s.state() + " @" + s.at() + "s"));
Output
A-1 SHIPPED @9s
A-2 PAID @4s
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