Java 8: Introduction to Streams API

Java 8 got a brand new API called streams. it makes every developer’s life easy. Stream APIs are used to process the group of data. mostly streams are applied on collection objects but we can use stream with any group of data.

The followings are more widely used operations of streams:

  • Iterate
  • Filter
  • Data Transformation
  • Sorting
  • Find Min and Max
  • Count the data
  • Much more…

Java Streams Methods

Java 8 Streams API has many methods but below are the most commonly used:

  • filter()
  • map()
  • forEach()
  • collect()
  • count()
  • distinct()
  • sorted()
  • toArray()
  • flatMap()
  • reduce()

We shall discuss each of the methods in detail. Remember that apart from the above methods Streams has many methods. Check out here.

Streams Creations

There are some ways to create a Stream in Java 8. We can create the stream using a group of data, Array or with Collections.

1. Create Empty Stream

				
					Stream<String> emptyStream = Stream.empty();
				
			

Stream.empty() method returns the empty stream object. This Empty Stream is used to avoid any null pointer exception.

2. Create Stream with Collection

				
					List<String> alpha = Arrays.asList("A","B","C","D");

Stream<String> alphaStream = alpha.stream();
				
			

From Java 8 onwards, the Collection interface got a new method called stream() which returns with Stream object of that particular collection object.

In the above example, alpha is a collection object and we can get the stream of alpha using alpha.stream() method

3. Create Stream with Primitive Array

				
					Stream<String> alphaStream = Stream.of("USA","UK","Japan","China");
				
			

It is also possible to get stream for set of values using Stream.of() method. We can also convert the existing primitive array to stream. 

For Example:

				
					String[] strArr = new String[] {"Apple","Banana","Orange","Kiwi"};
Stream<String> arrStream = Arrays.stream(strArr);
				
			

Conclusion

In this article, we have discussed the Streams API of the Java 8 version. Though we have given examples for beginners. we highly recommend reading more about other streams methods. You can check out here for more details. In the upcoming articles, we shall discuss all the methods of the stream with some examples. We would be happy if you leave your comments below.

Java 8 Stream APIs

Java 8: Introduction to Streams API

Java 8 got a brand new API called streams. it makes every developer’s life easy. Stream APIs are used to process the group of data. mostly streams are applied on collection objects but we can use stream with any group

Read More »