Interface Stream
A sequence of elements supporting sequential and parallel aggregate operations. The following example illustrates an aggregate operation using Stream and IntStream :
int sum = widgets.stream() .filter(w -> w.getColor() == RED) .mapToInt(w -> w.getWeight()) .sum();
In this example, widgets is a Collection
In addition to Stream , which is a stream of object references, there are primitive specializations for IntStream , LongStream , and DoubleStream , all of which are referred to as «streams» and conform to the characteristics and restrictions described here.
To perform a computation, stream operations are composed into a stream pipeline. A stream pipeline consists of a source (which might be an array, a collection, a generator function, an I/O channel, etc), zero or more intermediate operations (which transform a stream into another stream, such as filter(Predicate) ), and a terminal operation (which produces a result or side-effect, such as count() or forEach(Consumer) ). Streams are lazy; computation on the source data is only performed when the terminal operation is initiated, and source elements are consumed only as needed.
A stream implementation is permitted significant latitude in optimizing the computation of the result. For example, a stream implementation is free to elide operations (or entire stages) from a stream pipeline — and therefore elide invocation of behavioral parameters — if it can prove that it would not affect the result of the computation. This means that side-effects of behavioral parameters may not always be executed and should not be relied upon, unless otherwise specified (such as by the terminal operations forEach and forEachOrdered ). (For a specific example of such an optimization, see the API note documented on the count() operation. For more detail, see the side-effects section of the stream package documentation.)
Collections and streams, while bearing some superficial similarities, have different goals. Collections are primarily concerned with the efficient management of, and access to, their elements. By contrast, streams do not provide a means to directly access or manipulate their elements, and are instead concerned with declaratively describing their source and the computational operations which will be performed in aggregate on that source. However, if the provided stream operations do not offer the desired functionality, the BaseStream.iterator() and BaseStream.spliterator() operations can be used to perform a controlled traversal.
A stream pipeline, like the «widgets» example above, can be viewed as a query on the stream source. Unless the source was explicitly designed for concurrent modification (such as a ConcurrentHashMap ), unpredictable or erroneous behavior may result from modifying the stream source while it is being queried.
- must be non-interfering (they do not modify the stream source); and
- in most cases must be stateless (their result should not depend on any state that might change during execution of the stream pipeline).
Such parameters are always instances of a functional interface such as Function , and are often lambda expressions or method references. Unless otherwise specified these parameters must be non-null.
A stream should be operated on (invoking an intermediate or terminal stream operation) only once. This rules out, for example, «forked» streams, where the same source feeds two or more pipelines, or multiple traversals of the same stream. A stream implementation may throw IllegalStateException if it detects that the stream is being reused. However, since some stream operations may return their receiver rather than a new stream object, it may not be possible to detect reuse in all cases.
Streams have a BaseStream.close() method and implement AutoCloseable . Operating on a stream after it has been closed will throw IllegalStateException . Most stream instances do not actually need to be closed after use, as they are backed by collections, arrays, or generating functions, which require no special resource management. Generally, only streams whose source is an IO channel, such as those returned by Files.lines(Path) , will require closing. If a stream does require closing, it must be opened as a resource within a try-with-resources statement or similar control structure to ensure that it is closed promptly after its operations have completed.
Stream pipelines may execute either sequentially or in parallel. This execution mode is a property of the stream. Streams are created with an initial choice of sequential or parallel execution. (For example, Collection.stream() creates a sequential stream, and Collection.parallelStream() creates a parallel one.) This choice of execution mode may be modified by the BaseStream.sequential() or BaseStream.parallel() methods, and may be queried with the BaseStream.isParallel() method.
- Print elements in a stream
- Detailed Video Notes
- Getting started
- Method references
- Lambda
- Project set up
- Printing stream with method reference
- Printing with lambda
- Little fun
- Class PrintStream
- Field Summary
- Fields declared in class java.io.FilterOutputStream
- Constructor Summary
- Java stream print all
- Example of java.io.PrintStream class
- Example of printf() method of java.io.PrintStream class:
- Feedback
- Help Others, Please Share
- Learn Latest Tutorials
- Preparation
- Trending Technologies
- B.Tech / MCA
- Javatpoint Services
- Training For College Campus
Print elements in a stream
System.out.println is often used by developers for debugging purposes to examine elements or objects values present. Java 8 introduced streams so let’s find out how to print out elements in a stream using a lambda or method reference.
Detailed Video Notes
While better choice of capturing output of your program would be to choose a logging library such as commons logging, log4j you might be running a local java example where you want a light weight solution. Many developers turn to writing output to the console using System.out.print . With the introduction of streams in java 8, lets find out how we print the contents of a stream to the console.
Getting started
There are two concepts to understand before we dive into the code is method reference and lambdas.
Method references
Method references is a shorthand way to call a method directly which allows you to reuse existing method definitions. It is often a cleaner approach to refer to the existing method by name vs creating a lambda expression. The oracle java tutorials explain the kinds of method references. In our snippet we will reference the static method println so we will call ContainingClass::staticMethodName
Kind | Example |
---|---|
Reference to a static method | ContainingClass::staticMethodName |
Reference to an instance method of a particular object | containingObject::instanceMethodName |
Reference to an instance method of an arbitrary object of a particular type | ContainingType::methodName |
Reference to a constructor | ClassName::new |
Lambda
Lambda, introduced in java 8, provides a clean and concise way to call method while eliminating anonymous inner functions. In the wild they can typically be written like (int x, int y) -> x + y .
Project set up
Generating a java project from a maven archetype we will update the project to use java 8 and add the dependencies of junit.
Printing stream with method reference
First we need to create a Stream by using stream utility Stream.of which will create a sequential ordered stream of strings. Next calling the foreach, a terminal stream operation, we will pass in System.out::println which will loop over the elements and print the value. You can consider this a short hand way for looping over elements in an ArrayList.
Let’s run our test to see the result.
@Test public void print_elements_stream_method_reference() Stream.of("One", "Two", "Three", "Four").forEach(System.out::println); >
Printing with lambda
Using another type of stream, IntStream we will use the same technique we just showed you of creating a stream. Instead of using a method reference we will use a lambda expression which reads, pass each element of the stream to the System.out.println .
Let’s run our test to see the result.
@Test public void print_elements_stream_lambda() IntStream.of(1, 2, 3, 4).forEach( element -> System.out.println(element)); >
Little fun
You can see using the lambda expression gives you more flexibility especially if you want to append or change the element you are outputting. For instance, lets say before we loop over the elements we want to add 1 to each of the numbers. We can do this by using the lambda, calling the System.out and adding 1.
Let’s run our test to see the result.
@Test public void print_elements_stream_fun() IntStream.of(1, 2, 3, 4).forEach( element -> System.out.println(element + 1)); >
We hope that this tutorial showed you a few different ways to use foreach to loop over and print out the elements in a stream.
Thanks for joining in today’s level up, have a great day!
Print elements in a stream posted by Justin Musgrove on 16 March 2015
Tagged: java, java-tutorial, and java8
All the code on this page is available on github: View the source
Class PrintStream
A PrintStream adds functionality to another output stream, namely the ability to print representations of various data values conveniently. Two other features are provided as well. Unlike other output streams, a PrintStream never throws an IOException ; instead, exceptional situations merely set an internal flag that can be tested via the checkError method. Optionally, a PrintStream can be created so as to flush automatically; this means that the flush method of the underlying output stream is automatically invoked after a byte array is written, one of the println methods is invoked, or a newline character or byte ( ‘\n’ ) is written.
All characters printed by a PrintStream are converted into bytes using the given encoding or charset, or the platform’s default character encoding if not specified. The PrintWriter class should be used in situations that require writing characters rather than bytes.
This class always replaces malformed and unmappable character sequences with the charset’s default replacement string. The CharsetEncoder class should be used when more control over the encoding process is required.
Field Summary
Fields declared in class java.io.FilterOutputStream
Constructor Summary
Creates a new print stream, without automatic line flushing, with the specified file name and charset.
Creates a new print stream, without automatic line flushing, with the specified file name and charset.
Java stream print all
Example of java.io.PrintStream class
Example of printf() method of java.io.PrintStream class:
For Videos Join Our Youtube Channel: Join Now
Feedback
Help Others, Please Share
Learn Latest Tutorials
Preparation
Trending Technologies
B.Tech / MCA
Javatpoint Services
JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.
- Website Designing
- Website Development
- Java Development
- PHP Development
- WordPress
- Graphic Designing
- Logo
- Digital Marketing
- On Page and Off Page SEO
- PPC
- Content Development
- Corporate Training
- Classroom and Online Training
- Data Entry
Training For College Campus
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week
Like/Subscribe us for latest updates or newsletter