LongStream distinct() method in Java


The distinct() method in the LongStream class returns a stream consisting of the distinct elements of this stream.

The syntax is as follows.

LongStream distinct()

To use the LongStream class in Java, import the following package.

import java.util.stream.LongStream;

Create a LongStream and add elements.

LongStream longStream = LongStream.of(100L, 150L, 100L, 300L, 150L, 500L);

Now, get the distinct elements.

longStream.distinct().

The following is an example to implement LongStream distinct() method in Java. Here, we have repeated elements in the stream.

Example

 Live Demo

import java.util.stream.LongStream;
public class Demo {
   public static void main(String[] args) {
      LongStream longStream = LongStream.of(100L, 150L, 100L, 300L, 150L, 500L);
      System.out.println("Distinct elements...");
      longStream.distinct().forEach(System.out::println);
   }
}

Here is the output displaying only the distinct elements.

Output

Distinct elements...
100
150
300
500

Updated on: 30-Jul-2019

21 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements