The idea is to remember every value you have already seen. If adding a value to a HashSet fails, because add() returns false, that value is a duplicate. With streams, anyMatch() stops at the first duplicate, so you don't scan the rest of the array.
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class ContainsDuplicate {
static boolean containsDuplicate(int[] nums) {
Set<Integer> seen = new HashSet<>();
return Arrays.stream(nums).anyMatch(n -> !seen.add(n));
}
static boolean containsDuplicateDistinct(int[] nums) {
return Arrays.stream(nums).distinct().count() < nums.length;
}
public static void main(String[] args) {
System.out.println(containsDuplicate(new int[]{1, 2, 3, 1}));
System.out.println(containsDuplicate(new int[]{1, 2, 3, 4}));
System.out.println(containsDuplicateDistinct(new int[]{1, 1, 1, 3, 3, 4}));
}
}true
false
true
Using a stateful lambda (one that changes the seen set) is acceptable in a sequential stream, but it is not safe in a parallel stream. Saying this shows you understand stream side effects. In a real interview, the plain for-loop with a HashSet is often the cleanest answer.
A concise interview answer is
I add each number to a HashSet and return true as soon as add() returns false, which means the value was already seen. With streams that's Arrays.stream(nums).anyMatch(n -> !seen.add(n)), which runs in O(n) time and stops at the first duplicate.
Last updated: 11 November 2026
Previous question: Given a list of integers, sort the values in descending order using streams.
Next question: How do you get the current date and time using the Java 8 Date and Time API?