Multi-stream: merge two already-sorted feeds without re-sorting

Both feeds arrive in time order, so sorting the concatenation throws that away and pays O(n log n) to rebuild it. Walking two cursors is a single linear pass - the same merge step a real stream join uses.

Code
record Tick(String sym, int at, double px) {}

var acme = List.of(new Tick("ACME", 1, 10.0), new Tick("ACME", 5, 10.5), new Tick("ACME", 9, 10.2));
var beta = List.of(new Tick("BETA", 2, 20.0), new Tick("BETA", 6, 19.5));

var merged = new ArrayList<Tick>();
int i = 0, j = 0;
while (i < acme.size() || j < beta.size()) {
    boolean takeLeft = j == beta.size()
            || (i < acme.size() && acme.get(i).at() <= beta.get(j).at());
    merged.add(takeLeft ? acme.get(i++) : beta.get(j++));
}

merged.forEach(t -> System.out.println(t.at() + "s " + t.sym() + " " + t.px()));
Output
1s ACME 10.0
2s BETA 20.0
5s ACME 10.5
6s BETA 19.5
9s ACME 10.2
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