Java Stream distinct() with examples

 222 total views,  1 views today

Welcome to Java 8 series. In this tutorial, you will learn about java stream distinct() with examples.

distinct() is a part of the Stream pipeline and an intermediate operation. It belongs to the Stream interface.

distinct() operation allows us to fetch only distinct elements from the Stream by producing a new stream of distinct data.

Method description

Stream<T> distinct()

As per official documentation

Returns a stream consisting of the distinct elements (according to Object.equals(Object)) of this stream.

Since distinct() is an intermediate operation it will have two characteristics.

  1. distinct() is lazy loading operation. This means data will only be limited when a terminal operation is invoked on the stream.
  2. distinct() operation on a stream will always create a new stream output.

Let us now see a few examples of Java 8 stream distinct()

Java stream distinct() operation example

import java.util.ArrayList;
import java.util.List;

public class StaticReference {
	public static void main(String[] args) {
		List<String> list = new ArrayList<>();
		list.add("apple");
		list.add("orange");
		list.add("carrot");
		list.add("apple");
		list.add("ORANGE");

		list.stream().distinct().forEach(System.out::println);

	}
}

Output

apple
orange
carrot
ORANGE

In the above example, since apple is a duplicate element, only one apple is retained. Orange is not a duplicate because one is lowercase and other is Uppercase.

Conclusion

Java Stream distinct() operation is mainly used for producing a new stream with distinct elements. distinct() will always create a new stream and it is lazily evaluated.

References : Official documentation

Thanks for reading. Please a comment and give us a thumbs up! 

Tags :

About the Author

Rajasekar

Hey There, My name is Rajasekar and I am the author of this site. I hope you are liking my tutorials and references. Programming and learning new technologies are my passion. The ultimate idea of this site is to share my knowledge(I am still a learner :)) and help you out!. Please spread your words about us (staticreference.com) and give a thumbs up :) Feel free to contact me for any queries!.