Vijay
Vijay

Reputation: 573

Find Distinct Elements in a List of Integer without using distinct() method using Stream API

I have been asked the following question in a recent Java interview:

Find a list of distinct elements from a list of integers without using distinct() method using Java 8 Stream API only.

It is obvious to use distinct() method with Stream API for that purpose. But I was specifically asked to use something else.

Upvotes: 0

Views: 334

Answers (1)

Alexander Ivanchenko
Alexander Ivanchenko

Reputation: 28978

To answer this interview question properly, you were expected to demonstrate knowledge on how distinct() works.

According to the documentation, distinct() - is a stateful intermediate operation. Under the hood, it maintains a LinkedHashSet to insure uniqueness of the elements and at the same time preserve the initial order of the stream (if the stream is ordered).

In case if we don't care about the order, we can store elements into a general purpose implementation of the Set interface - HashSet. That's how we can write this code using a stream:

List<Integer> uniqueElements = new ArrayList<>(
    sourceList.stream().collect(Collectors.toSet())
);

And I guess that you might be also expected to make a conclusion that there's no need to generate a stream pipeline and then make use of a collector just in order to dump all list elements into a set. Because it's a convoluted and less efficient way to do the same thing that can be done by using a parameterized constructor of the HashSet class:

List<Integer> uniqueElements = new ArrayList<>( new HashSet<>(sourceList) );

Upvotes: 4

Related Questions