Multi-stream: union, intersection and difference of two lists

The four set questions people ask of two feeds, each a filter against a Set built once. Copying the other side into a Set first is what keeps every membership test O(1) instead of a nested scan.

Code
var teamA = List.of("ava", "ben", "cara", "dan");
var teamB = List.of("cara", "dan", "eve");

var inA = Set.copyOf(teamA);
var inB = Set.copyOf(teamB);

System.out.println("union       : " + Stream.concat(teamA.stream(), teamB.stream()).distinct().sorted().toList());
System.out.println("intersection: " + teamA.stream().filter(inB::contains).sorted().toList());
System.out.println("only in A   : " + teamA.stream().filter(n -> !inB.contains(n)).sorted().toList());
System.out.println("only in B   : " + teamB.stream().filter(n -> !inA.contains(n)).sorted().toList());
Output
union       : [ava, ben, cara, dan, eve]
intersection: [cara, dan]
only in A   : [ava, ben]
only in B   : [eve]
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