Java: Deduplicate while keeping order with distinct

Stream.distinct removes duplicates using equals, preserving encounter order.

Code
List<Integer> nums = List.of(3, 1, 2, 3, 1, 4);
System.out.println(nums.stream().distinct().toList());
Output
[3, 1, 2, 4]
Advertisement

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-07-26