Junior — Middle
What is the purpose of the distinct method in the Stream API and how does it differ from other filtering methods?
sobes.tech AI
Answer from AI
The distinct() method in the Stream API is used to remove duplicates from a stream of elements. It returns a new stream where each element is unique, based on the equals() and hashCode() methods of the objects.
It differs from other filtering methods like filter() in that distinct() automatically eliminates repeated elements, while filter() allows you to specify an arbitrary condition for selecting elements.
Example:
List<Integer> numbers = Arrays.asList(1, 2, 2, 3, 4, 4, 5);
List<Integer> distinctNumbers = numbers.stream()
.distinct()
.collect(Collectors.toList());
// distinctNumbers will contain [1, 2, 3, 4, 5]