Approach 1: Using Stream.distinct()
import java.util.*; import java.util.stream.*; List<Integer> nums = Arrays.asList(1,2,2,3,3,3,4); List<Integer> distinct = nums.stream() .distinct() .collect(Collectors.toList()); System.out.println(distinct); // [1, 2, 3, 4]
Why it works:
distinct()
uses theequals()
andhashCode()
methods to filter duplicates.- It preserves the encounter order of the first occurrences.
Approach 2: Using LinkedHashSet
(Alternative)
List<Integer> nums = Arrays.asList(1,2,2,3,3,3,4); List<Integer> distinct = new ArrayList<>(new LinkedHashSet<>(nums)); System.out.println(distinct); // [1, 2, 3, 4]
Why it works:
LinkedHashSet
automatically removes duplicates.- Preserves insertion order.
- Alternative to streams for cases where you want collection-based deduplication.