In Java programs, we normally use System.out.println() to print values of an Object we want to see.
But with Streams, the intermediate operations don’t run until needed. So, its a little trickier..
Here are some approaches we can use to print the stream contents.
Using forEach
Stream<String> streamCountries = Stream.of("Germany", "England", "China", "Denmark", "Brazil"); streamCountries.forEach(s->System.out.println(s));
We can also write this as :
streamCountries.forEach(System.out::println);
Output :
Germany
England
China
Denmark
Brazil
However, note that this approach destroys the stream. So, it won’t exist for the next operation you may be using on the stream.
For example, if you have code like this, you will receive an error since the stream is already destroyed.
Stream<String> streamCountries = Stream.of("Germany", "England", "China", "Denmark", "Brazil"); streamCountries.forEach(System.out::println); streamCountries.filter(s->s.startsWith("E")).forEach(System.out::println);
Output :
Germany
England
China
Denmark
Brazil
Exception in thread “main” java.lang.IllegalStateException: stream has already been operated upon or closed
Using println() with collect()
Stream<String> s = Stream.of("Germany", "England", "China", "Denmark", "Brazil"); System.out.println(s.collect(Collectors.toList()));
Output :
[Germany, England, China, Denmark, Brazil]
This approach also destroys the Stream.
Using peek()
Stream<String> stream = Stream.of("Germany", "England", "China", "Denmark", "Brazil"); stream.filter(s -> s.startsWith("D")) .peek(s -> System.out.println("Filtered value: " + s)) .map(String::toUpperCase) .peek(s -> System.out.println("Uppercase value :" + s)).count();
Output :
Filtered value: Denmark
Uppercase value :DENMARK
Since peek() is an intermediate operation, it doesn’t destroy the stream. Therefore, the stream will remain available with subsequent operations as shown in this example.
This method exists mainly to support debugging, where you want to see the elements as they flow past a certain point in a pipeline.
© 2016, https:. All rights reserved. On republishing this post, you must provide link to original post