Friday, March 29, 2024
HomeJava10 Examples of Stream Class in Java 8

10 Examples of Stream Class in Java 8 [ map + filter+ flatmap + collect + findFirst ]


There isn’t any doubt that Stream class is among the most vital class of Java SE 8 API and a strong information of this class is required to put in writing modern-day Java code. There isn’t any excuse to put in writing the Java code we used to put in writing in crucial type like utilizing loops and never utilizing practical programming idioms. The truth is, now it is one of many finest apply in Java to favor practical programming and immutable information construction over crucial programming. Increasingly Technical Leads are imposing builders to study Java 8 and write higher code leveraging improved API. The Java designers has finished a unbelievable job to transform any assortment to Stream by including stream() methodology into Assortment interface. 

When you get the Stream with components you possibly can apply a lot of the practical programming ideas e.g. map, filter, flatMap, cut back simply. There are tons of such strategies into Stream class and on this article, I’m going to elucidate a very powerful one. 

Keep in mind the 80/20 rule of Ranga Karnam, writer of well-known Spring Masterclass course on Udemy, who concentrate on instructing the 20% vital stuff which we occur to make use of 80% of time. I’m following a few of his recommendation on this article and as a substitute of explaining each single methodology of Stream class, I’ve selected a very powerful ones which Java builders will almost definitely use of their day after day life. 

The right way to Be taught Stream API by Examples in Java

Here’s a record of strategies from Stream class we’ll discover on this article:

we’ll see a quick description of the strategy like what it does and when to make use of it adopted by a easy instance which you’ll bear in mind. 

1. Stream.map() Instance

The map() operate is used to remodel Stream of 1 sort of object to Stream of one other sort of object. It settle for a way which it may well apply on every component of Stream to remodel the article. For instance, by utilizing map() methodology you possibly can convert a Stream of Integer to Stream of String by making use of the valueOf() methodology on every component. 
Record<Integer> listOfIntegers = enter.stream()
.map(Integer::valueOf)
.gather(Collectors.toList());

System.out.println("record of string: " + enter);
System.out.println("record of integer utilizing Stream.map(): " + listOfIntegers);

Output: 
record of string: [1, 20, 300, 4000, 5000, 60000]
record of integer utilizing Stream.map(): [1, 20, 300, 4000, 5000, 60000]

You possibly can see that we’ve efficiently transformed record of String to record of Integer by making use of Integer.valueOf() methodology to every component utilizing map() operate. 

2. Stream.filter() Instance

Because the identify suggests, the filter methodology can filter components in Stream, however it works extra like choose then filter. You present a boolean situation, which is utilized to all the weather and solely these handed the circumstances are current in new Stream. The situation is specified utilizing Predicate interface, which is a practical interface and symbolize a operate which accepts a sort and return a Boolean. 

right here is an instance of filter() methodology of Stream class to pick out String whose size is bigger than two:

Record<String> listOfStringWithLengthGreaterThanTwo = enter.stream()
                         .filter(s->> s.size() > 2)
                         .gather(Collectors.toList()); 
System.out.println("authentic record of string: " + enter);
System.out.println("filtered record of String with size higher than 2 utilizing
Stream.map(): " + listOfStringWithLengthGreaterThanTwo);

Output:
authentic record of string: [1, 20, 300, 4000, 5000, 60000]
filtered record of String with size higher than 2 utilizing Stream.map(): 
[300, 4000, 5000, 60000]

You possibly can see that solely String with size higher than two are current within the filtered record. String e.g. “1”, “20” which has size two or lower than two had been filtered out.

10 Examples of Stream Class in Java 8 [ map + filter+ flatmap  + collect + findFirst ]

3. Stream.flatMap() Instance

The flatmap() operate works like map i.e. it remodel one object to a different however along with transformation it additionally used for flattening the Stream. For instance you probably have an inventory of record then you possibly can convert it into only a large record by utilizing flatMap() operate. 
Record<Record<Integer>> unflattened = new ArrayList<>();
unflattened.add(Arrays.asList(1, 3, 5));
unflattened.add(Arrays.asList(2, 4, 6));

Record<Integer> flattenedList = unflattened.stream()
                                         .flatMap(record->> record.stream())
                                         .gather(Collectors.toList());
System.out.println("unflattend record : " + unflattened);
System.out.println("flattend record : " + flattenedList);

Output:
unflattend record : [[1, 3, 5], [2, 4, 6]]
flattend record : [1, 3, 5, 2, 4, 6]
You possibly can see that flattened record comprises all the weather from particular person record. You can too present a metamorphosis operate similar to we did to map however I depart that to you. In case you want some help you possibly can see these examples of flatMap operate for extra particulars. 

4. Stream.toArray() Instance

The toArray() methodology of Stream class can be utilized to transform a Stream into an array in Java. One of many problem changing record to array was the kind of array as they do not assist generics. However, with Stream you needn’t fear, you possibly can specify a Provider as constructor reference on toArray() methodology to build up components in the proper of array. 

right here is an exampel of changing a Stream of String into an String array in in Java:

String[] array = enter.stream().toArray(String[]::new);
System.out.println("array created utilizing Stream.toArray(): " + array);

Output:
array created utilizing Stream.toArray(): [Ljava.lang.String;@3d075dc0
The output is not pretty because we have directly printed the array. If you want a more meaningful value, use the Arrays.toString(array) which will print the elements of array instead of hashcode. 

5. Stream.distict() Example

The distinct method of Stream class is like the distinct keyword of SQL, both removes duplicates. You can use distinct() method to get only unique values form Stream. 

here is an example of collecting unique values of a Stream into a List in Java 8 using Stream.distinct() method:

List<String> withoutDupes = input.stream()
                                 .distinct()
                                 .collect(Collectors.toList());
System.out.println("original list of string: " + input);
System.out.println("list of string wihtout dupliates using Stream.distinct(): " 
 + withoutDupes);

Output:
original list of string: [1, 20, 300, 4000, 5000, 60000]
record of string wihtout dupliates utilizing Stream.distinct(): 
[1, 20, 300, 4000, 5000, 60000]

Since, our record did not include any duplicate the variety of components in each authentic and processed record is similar. Simply add a reproduction within the authentic record and see how that’s eliminated utilizing distinct() methodology. 

6. Stream.sorted() Instance

The sorted() methodology of Stream class can be utilized to type a Stream in Java. Since Stream retains the component within the order, it is doable to type them on any customized order specified by Comparator. 

Right here is an instance of sorting a Stream within the reverse order:

Record<String> sortedInDescendingOrder = enter.stream()
                                    .sorted(Comparator.reverseOrder())
                                    .gather(Collectors.toList());
System.out.println("authentic record of string: " + enter);
System.out.println("sorted record of String utilizing Stream.sorted() : " 
                                + sortedInDescendingOrder);

Output:
authentic record of string: [1, 20, 300, 4000, 5000, 60000]
sorted record of String utilizing Stream.sorted() : [60000, 5000, 4000, 300, 20, 1]

You possibly can see that components of Stream.sorted() are printed in reverse order than it was within the authentic record.

7. Stream.peek() Instance

The peek() methodology of Stream class is usually a great tool for debugging a Stream pipeline and lambda expression. You need to use the peek() to seek out out what taking place in every stage of Stream processing pipeline. 
For instance, in following code, we’ve used peek() to print the component after filter however within the output we solely see 300 and never different values. This occurs as a result of Stream is lazy and because the terminal methodology is findFirst() solely the primary component whose size is bigger than 2 is returned. 
String outcome = enter.stream()
.filter(s->> s.size() > 2)
.peek(System.out::println)
.findFirst().orElse("");

System.out.println("filtered record: " + outcome);

Output:
300
filtered record: 300 

Through the use of peek() within the above instance, we will affirm that Stream processing is lazy. The filter methodology did not filter all object of Stream as a substitute, processing solely lasted till the reply is discovered. 

8. Steram.of() Instance

The of() is a static manufacturing unit methodology of Stream class which can be utilized to create a Stream of arbitrary values. In a lot of the instances, you’ll get Stream from Assortment e.g. record or set however in some instances you might have to create Stream your self, and Stream.of() is ideal for these instances. 

The strategy is overloaded to create Stream of 1, two, three, or extra object in Java. The final model accepts a variable arguments which lets you create Stream or any variety of components.

Right here is an instance of Stream.of() mthod in Java:

Stream<Integer> streamOfPrimeNumbers = Stream.of(2, 3, 5, 7, 11, 13, 17)
System.out.println("stream of prime numbers: " + streamOfPrimeNumbers);

Output:

stream of prime numbers: java.util.stream.ReferencePipeline$Head@58372a00

You possibly can see that the output isn’t very helpful as a result of in contrast to Assortment class, Stream does not appear to override the toString() methodology. 

9. Stream.gather() Instance

The gather() methodology is among the most vital methodology of Stream class. It offers the bridge between Stream and Assortment. You need to use gather to transform a Stream to a Record, Set, Map, or some other Assortment in Java. 
It accepts a Collector which can be utilized to build up objects of Stream into specified Assortment. The Collectors class offers a number of utility methodology to transform Stream to record, set, and map. 

Right here is an instance to transform a Stream of String into an ArrayList of Integer in Java 8:

ArrayList<Integer> arrayListOfIntegers = enter.stream()
                           .map(Integer::valueOf)
                           .gather(Collectors.toCollection(ArrayList::new));
System.out.println("authentic record of string: " + enter);
System.out.println("ArrayList of Integers utilizing Stream.gather(): " 
 + arrayListOfIntegers);

Output:
authentic record of string: [1, 20, 300, 4000, 5000, 60000]
ArrayList of Integers utilizing Stream.gather(): [1, 20, 300, 4000, 5000, 60000]

You may even see that output of each the record is similar as a result of we’re finally printing the String however first record is a of Sting objects whereas ArrayList comprises Integer objects. 

10. Stream.findFirst() Instance

The findFirst() methodology of Stream class return the primary component of Stream. Exactly it return an Non-compulsory as a result of it is doable that Stream could also be empty and there will not be any component on it. 

Right here is an instance of findFirst() methodology which both return first elment or an empty String:

String firstStringFromStream = enter.stream().findFirst().orElse("");
System.out.println("authentic record of string: " + enter);
System.out.println("first component from Stream: " + firstStringFromStream);

Output:
authentic record of string: [1, 20, 300, 4000, 5000, 60000]
first component from Stream: 1

You possibly can see that the primary component of Stream has returned. You possibly can additional do that methodology on an empty Stream and see what occurs.

Java Program to Be taught Stream API by Examples 

Right here is our full Java program to display learn how to use numerous strategies of Stream class in Java 8. This program comprises all above examples and you’ll simply copy paste and run it on Eclipse Java IDE. You do not even have to create a Java class, simply copy paste it in your Java challenge and Eclipse will deal with it. You can too mess around by altering the enter and attempting with completely different sort of Record. 
bundle device;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Record;
import java.util.stream.Collectors;
import java.util.stream.Stream;




public class Whats up {

public static void foremost(String[] args) {


Record<String> enter = Arrays.asList("1", "20", "300", "4000", "5000", "60000");



Record<Integer> listOfIntegers 
= enter.stream().map(Integer::valueOf).gather(Collectors.toList());
System.out.println("record of string: " + enter);
System.out.println("record of integer utilizing Stream.map(): " + listOfIntegers);



Record<String> listOfStringWithLengthGreaterThanTwo 
= enter.stream().filter(s->> s.size() > 2).gather(Collectors.toList()); 
System.out.println("authentic record of string: " + enter);
System.out.println("filtered record of String with size higher than 2 utilizing Stream.map():
 " + listOfStringWithLengthGreaterThanTwo);



Record<Record<Integer>> unflattened = new ArrayList<>();
unflattened.add(Arrays.asList(1, 3, 5));
unflattened.add(Arrays.asList(2, 4, 6));

Record<Integer> flattenedList 
= unflattened.stream().flatMap(list->> record.stream()).gather(Collectors.toList());
System.out.println("unflattend record : " + unflattened);
System.out.println("flattend record : " + flattenedList);



String[] array = enter.stream().toArray(String[]::new);
System.out.println("array created utilizing Stream.toArray(): " + array);



Record<String> withoutDupes = enter.stream().distinct().gather(Collectors.toList());
System.out.println("authentic record of string: " + enter);
System.out.println("record of string wihtout dupliates utilizing Stream.distinct(): " 
+ withoutDupes);



Record<String> sortedInDescendingOrder 
= enter.stream().sorted(Comparator.reverseOrder()).gather(Collectors.toList());
System.out.println("authentic record of string: " + enter);
System.out.println("sorted record of String utilizing Stream.sorted() : " 
+ sortedInDescendingOrder);



String firstStringFromStream = enter.stream().findFirst().orElse("");
System.out.println("authentic record of string: " + enter);
System.out.println("first component from Stream: " + firstStringFromStream);



Stream<Integer> streamOfPrimeNumbers = Stream.of(2, 3, 5, 7, 11, 13, 17);
System.out.println("stream of prime numbers: " + streamOfPrimeNumbers);



ArrayList<Integer> arrayListOfIntegers 
= enter.stream().map(Integer::valueOf).gather(Collectors.toCollection(ArrayList::new));
System.out.println("authentic record of string: " + enter);
System.out.println("ArrayList of Integers utilizing Stream.gather(): " 
+ arrayListOfIntegers);



String outcome = enter.stream()
.filter(s->> s.size() > 2)
.peek(System.out::println)
.findFirst().orElse("");

System.out.println("filtered record: " + outcome);
}

}

Output:
record of string: [1, 20, 300, 4000, 5000, 60000]
record of integer utilizing Stream.map(): [1, 20, 300, 4000, 5000, 60000]
authentic record of string: [1, 20, 300, 4000, 5000, 60000]
filtered record of String with size higher than 2 utilizing Stream.map():
 [300, 4000, 5000, 60000]
unflattend record : [[1, 3, 5], [2, 4, 6]]
flattend record : [1, 3, 5, 2, 4, 6]
array created utilizing Stream.toArray(): [Ljava.lang.String;@3d075dc0
original list of string: [1, 20, 300, 4000, 5000, 60000]
record of string wihtout dupliates utilizing Stream.distinct(): 
[1, 20, 300, 4000, 5000, 60000]
authentic record of string: [1, 20, 300, 4000, 5000, 60000]
sorted record of String utilizing Stream.sorted() : [60000, 5000, 4000, 300, 20, 1]
authentic record of string: [1, 20, 300, 4000, 5000, 60000]
first component from Stream: 1
stream of prime numbers: java.util.stream.ReferencePipeline$Head@58372a00
authentic record of string: [1, 20, 300, 4000, 5000, 60000]
ArrayList of Integers utilizing Stream.gather(): [1, 20, 300, 4000, 5000, 60000]
300
filtered record: 300

Vital Factors about Stream class in Java 8

Now that you’ve got seen a few of the important strategies of Stream class and discovered how and when to make use of them, it is time to revise no matter you’ve gotten discovered thus far. 

1) Use map() methodology to remodel Stream of 1 sort to a different. 

2) Use filter() methodology to pick out components from Stream primarily based upon some circumstances.

3) Use flatMap() methodology to each flatten the Stream in addition to remodel it like map methodology.

4) The toArray() methodology is used to transform Stream to array in Java. 

5) The distinct methodology can be utilized to take away duplicate components from Stream. 

6) The sorted methodology of Stream can be utilized to type components of Stream of their pure order or a customized order outlined by Comparator. 

7) The peek methodology can be utilized for debugging a Stream pipeline. It may print messages after every operation on Stream.

8) The static manufacturing unit methodology Stream.of() can be utilized to create Stream from given objects. 

9) The gather() methodology of Stream class can be utilized to gather the weather of Stream into completely different sort of Assortment objects like Record, Set or Map with the assistance of Collectors. 

10 The findFirst() methodology can be utilized to retrieve the primary component from Stream. 

That is all about examples of important strategies of Stream class in Java.  After you have goe by means of these examples, you’d discover ways to use Stream API and when to make use of these strategies. Though Stream class is large and obtained much more strategies, these are these 20% of strategies which you’ll use 80% of time. 

I’ve defined all these strategies with an instance of Record of integers and as an train you possibly can check out all these methodology by utilizing Record of String. That won’t solely assist you to to higher perceive their utilization but in addition develop the intiuition and coding sense you want whereas writing code in Java 8. In case you want any assist you possibly can all the time refer following sources for refernece:

Different Java 8 and Stream articles you might like:

  • High 5 Programs to Be taught Java 8 Programming (programs)
  • 16 Stream and Lambda Interview questions (stream questions)
  • Java 8 map + filter + stream instance (tutorial)
  • 15 Java Stream and Purposeful Programming questions (practical questions)
  • The right way to be a part of String in Java 8 (instance)
  • 5 Books to Be taught Java 8 from Scratch (books)
  • The right way to use Stream class in Java 8 (tutorial)
  • The right way to examine two Dates in Java 8? (instance)
  • 10 Java Date, Time, and Calendar primarily based Questions from Interviews (questions)
  • The right way to format/parse the date with LocalDateTime in Java 8? (tutorial)
  • 10 Examples to format and parse Date in Java 8? (tutorial)
  • The right way to use forEach() methodology in Java 8 (instance)
  • The right way to change the date format of String in Java 8? (tutorial)
  • The right way to convert Timestamp to Date in Java? (instance)
  • 20 Examples to study new Date and Time API in Java 8 (instance)
  • 5 Free Programs to study Java 8 and 9 (programs)
  • 50 Java 8 Stream and Lambda Interview questions (java 8 questions)

Thanks for studying this text thus far. In case you like these Stream examples and if this tutorial helped you to study Stream API higher than please share with your mates in Fb and Twitter. You probably have any questions or suggestions then please drop a word.

P. S. – If you wish to study Stream class and API in depth and on the lookout for on-line programs then it’s also possible to checkout these Stream and Assortment on-line programs the place I’ve shared finest on-line programs to study Stream API in Java. 



RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments