简体   繁体   中英

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.

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) );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM