Chapters
This class holds sequence of elements supporting sequential and parallel aggregate operations. 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
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. In other words, if we want to get a result from a Stream, we need to initiate a terminal operation. The explanation in this tutorial is simplified. More information can be found in this article and this another article.
In this tutorial, we're going to use collections(ArrayList, LinkedList, etc.) and arrays as our source. Collection interface has
This example demonstrate the usage of Stream.
Then, we call the
Lastly, we call
Like
The first parameter is a Supplier type. Stream initializes multiple instances of this parameter to hold the elements that we're gonna accumulate in the source. The second parameter is a BiConsumer type. This parameter accepts a lambda expression that supplies suppliers with elements of the source. The third parameter is also a BiConsumer type. This parameter concatenates results from multiple accumulators that run in parallel.
I'll demonstrate some methods of Stream class in this tutorial. More methods can be seen in the documentation.
Method form:
Returns whether all elements of this stream match the provided predicate. May not evaluate the predicate on all elements if not necessary for determining the result. If the stream is empty then true is returned and the predicate is not evaluated. This is a short-circuiting terminal operation.
Method form:
Returns a String.Builder object for a Stream.
This method has two forms. One of its forms has been explained in the first topic. In this topic, I'm gonna demonstrate this form.
Method form:
This method performs a mutable reduction operation on the elements of this stream using a Collector. A Collector encapsulates the functions used as arguments to
If the stream is parallel, and the Collector is concurrent, and either the stream is unordered or the collector is unordered, then a concurrent reduction will be performed (see Collector for details on concurrent reduction.) This is a terminal operation.
When executed in parallel, multiple intermediate results may be instantiated, populated, and merged so as to maintain isolation of mutable data structures. Therefore, even when executed in parallel with non-thread-safe data structures (such as ArrayList), no additional synchronization is needed for a parallel reduction.
Method form:
Creates a lazily concatenated stream whose elements are all the elements of the first stream followed by all the elements of the second stream. The resulting stream is ordered if both of the input streams are ordered, and parallel if either of the input streams is parallel. When the resulting stream is closed, the close handlers for both input streams are invoked.
This method operates on the two input streams and binds each stream to its source. As a result subsequent modifications to an input stream source may not be reflected in the concatenated stream result.
This method returns the count of elements in this stream. This is a special case of a reduction and is equivalent to:
This is a terminal operation.
Returns a stream consisting of the distinct elements (according to
Method form:
If this stream is ordered then the longest prefix is a contiguous sequence of elements of this stream that match the given predicate. The first element of the sequence is the first element of this stream, and the element immediately following the last element of the sequence does not match the given predicate.
If this stream is unordered, and some (but not all) elements of this stream match the given predicate, then the behavior of this operation is nondeterministic; it is free to drop any subset of matching elements (which includes the empty set).
Independent of whether this stream is ordered or unordered if all elements of this stream match the given predicate then this operation drops all elements (the result is an empty stream), or if no elements of the stream match the given predicate then no elements are dropped (the result is the same as the input). This is a stateful intermediate operation.
Streams may or may not have a defined encounter order. Whether or not a stream has an encounter order depends on the source and the intermediate operations. Certain stream sources (such as List or arrays) are intrinsically ordered, whereas others (such as HashSet) are not. Some intermediate operations, such as sorted(), may impose an encounter order on an otherwise unordered stream, and others may render an ordered stream unordered.
Method form:
Returns a stream consisting of the elements of this stream that match the given predicate.
Method form:
Returns an Optional describing some element of the stream, or an empty Optional if the stream is empty. This is a short-circuiting terminal operation.
The behavior of this operation is explicitly nondeterministic; it is free to select any element in the stream. This is to allow for maximal performance in parallel operations; the cost is that multiple invocations on the same source may not return the same result. (If a stable result is desired, use
Returns an Optional describing the first element of this stream, or an empty Optional if the stream is empty. If the stream has no encounter order, then any element may be returned. This is a short-circuiting terminal operation.
Method form:
Returns a stream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element. Each mapped stream is closed after its contents have been placed into this stream. (If a mapped stream is null an empty stream is used, instead.) This is an This is a intermediate operation.
Flattening is a process of merging several layers into one single layer. When we flatten an array(or collection), we get all elements from arrays within the array and merge all elements in a one-dimensional array.
Here's another example. This time, we're gonna modify the mapped values.
Mapping is a process of associating an element from a set to another set. Association of elements could be copying an element to another set, generating new elements from elements in the set, etc.
There are methods that are associated with
This example demonstrates
Method form:
Performs an action for each element of this stream. This is a terminal operation. The behavior of this operation is explicitly nondeterministic. For parallel stream pipelines, this operation does not guarantee to respect the encounter order of the stream, as doing so would sacrifice the benefit of parallelism.
For any given element, the action may be performed at whatever time and in whatever thread the library chooses. If the action accesses shared state, it is responsible for providing the required synchronization.
Performs an action for each element of this stream, in the encounter order of the stream if the stream has a defined encounter order. This is a terminal operation. This operation processes the elements one at a time, in encounter order if one exists.
Performing the action for one element happens-before performing the action for subsequent elements, but for any given element, the action may be performed in whatever thread the library chooses. In multithreading,
Method form:
Returns an infinite sequential unordered stream where each element is generated by the provided Supplier. This is suitable for generating constant streams, streams of random elements, etc.
This example demonstrate
This method has two forms. Let's start with this form:
Method form:
This method returns a sequential ordered Stream produced by iterative application of the given next function to an initial element, conditioned on satisfying the given hasNext predicate. The stream terminates as soon as the hasNext predicate returns false.
The resulting sequence may be empty if the hasNext predicate does not hold on the seed value. Otherwise the first element will be the supplied seed value, the next element (if present) will be the result of applying the next function to the seed value, and so on iteratively until the hasNext predicate indicates that the stream should terminate.
The action of applying the hasNext predicate to an element happens-before the action of applying the next function to that element. The action of applying the next function for one element happens-before the action of applying the hasNext predicate for subsequent elements. For any given element an action may be performed in whatever thread the library chooses.
This method returns an infinite sequential ordered Stream produced by iterative application of a function f to an initial element seed, producing a Stream consisting of seed, f(seed), f(f(seed)), etc. The first element (position 0) in the Stream will be the provided seed. For n > 0, the element at position n, will be the result of applying the function f to the element at position n - 1.
The action of applying f for one element happens-before the action of applying f for subsequent elements. For any given element the action may be performed in whatever thread the library chooses.
Method form:
Returns a stream consisting of the results of applying the given function to the elements of this stream. This is an intermediate operation.
This example demonstrates
Mapping is a process of associating an element from a set to another set. Association of elements could be copying an element to another set, generating new elements from elements in the set, etc.
Method form:
Returns a stream consisting of the results of replacing each element of this stream with multiple elements, specifically zero or more elements. Replacement is performed by applying the provided mapping function to each element in conjunction with a consumer argument that accepts replacement elements. The mapping function calls the consumer zero or more times to provide the replacement elements.
This is an intermediate operation. If the consumer argument is used outside the scope of its application to the mapping function, the results are undefined. This method is similar to flatMap in that it applies a one-to-many transformation to the elements of the stream and flattens the result elements into a new stream.
If a lambda expression is provided as the mapper function argument, additional type information may be necessary for proper inference of the element type <R> of the returned stream. This can be provided in the form of explicit type declarations for the lambda parameters or as an explicit type argument to the mapMulti call.
This is how we achieve the result above using
There are methods that are associated with
This example demonstrates
Method form:
This method is a terminal operation that performs a reduction that specializes in finding the maximum element of the stream according to the provided Comparator. This method returns an Optional<T> object.
Method form:
This method is a terminal operation that performs a reduction that specializes in finding the minimum element of the stream according to the provided Comparator. This method returns an Optional<T> object.
Method form:
Returns whether no elements of this stream match the provided predicate. May not evaluate the predicate on all elements if not necessary for determining the result. If the stream is empty then true is returned and the predicate is not evaluated. This is a short-circuiting terminal operation.
This method has two forms.
This example demonstrates
Method form:
Returns a sequential Stream containing a single element, if non-null, otherwise returns an empty Stream.
Method form:
Returns a stream consisting of the elements of this stream, additionally performing the provided action on each element as elements are consumed from the resulting stream. This is an intermediate operation.
For parallel stream pipelines, the action may be called at whatever time and in whatever thread the element is made available by the upstream operation. If the action modifies shared state, it is responsible for providing the required synchronization.
This method exists mainly to support debugging, where you want to see the elements as they flow past a certain point in a pipeline:
This method has three forms. Let's start with this form:
This terminal operation performs a reduction on the elements of this stream, using an associative accumulation function, and returns an Optional describing the reduced value, if any. The accumulator function must be an associative function. Reduction operations can be parallelized without requiring additional synchronization.
Next, let's discuss the last form:
Take note, use
Method form:
Returns a stream consisting of the remaining elements of this stream after discarding the first n elements of the stream. If this stream contains fewer than n elements then an empty stream will be returned. This is a stateful intermediate operation.
Returns, if this stream is ordered, a stream consisting of the longest prefix of elements taken from this stream that match the given predicate. Otherwise returns, if this stream is unordered, a stream consisting of a subset of elements taken from this stream that match the given predicate.
If this stream is ordered then the longest prefix is a contiguous sequence of elements of this stream that match the given predicate. The first element of the sequence is the first element of this stream, and the element immediately following the last element of the sequence does not match the given predicate.
If this stream is unordered, and some (but not all) elements of this stream match the given predicate, then the behavior of this operation is nondeterministic; it is free to take any subset of matching elements (which includes the empty set).
Independent of whether this stream is ordered or unordered if all elements of this stream match the given predicate then this operation takes all elements (the result is the same as the input), or if no elements of the stream match the given predicate then no elements are taken (the result is an empty stream). This is a short-circuiting stateful intermediate operation.
- Stream and its Pipeline
- allMatch() Method
- anyMatch() Method
- builder() Method
- collect() Method
- concat() Method
- count() Method
- distinct() Method
- dropWhile() Method
- filter() Method
- findAny() Method
- findFirst() Method
- flatMap() Method
- forEach() Method
- forEachOrdered() Method
- generate() Method
- iterate() Method
- map() Method
- mapMulti() Method
- max() Method
- min() Method
- noneMatch() Method
- of() Method
- ofNullable() Method
- peek() Method
- reduce() Method
- skip() Method
- takeWhile() Method
Stream and its Pipeline
This class holds sequence of elements supporting sequential and parallel aggregate operations. 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. In other words, if we want to get a result from a Stream, we need to initiate a terminal operation. The explanation in this tutorial is simplified. More information can be found in this article and this another article.
In this tutorial, we're going to use collections(ArrayList, LinkedList, etc.) and arrays as our source. Collection interface has
stream()
method that returns a sequential stream. stream()
is a default method of Collection interface. Thus, every collections that extend Collection can access the method. You need to be knowledgable about lambda expression and generics to understand this tutorial.
This example demonstrate the usage of Stream.
import java.util.stream.Stream; import java.util.ArrayList; public class SampleClass{ public static void main(String[] args){ ArrayList<String> ar = new ArrayList<>(); ar.add("Apple"); ar.add("Melon"); ar.add("Mango"); ar.add("Avocado"); ar.add("Watermelon"); ar.add("Mangosteen"); Object[] subFruits = ar.stream() .filter(f -> f.startsWith("M")) .sorted().toArray(); System.out.println("Fruits that start " +"with \"M\""); for(Object obj : subFruits) System.out.println(obj); } } Result Fruits that start with "M" Mango Mangosteen MelonIn the example above, we call the
stream()
method of ArrayList that returns a sequential stream that uses ArrayList as its source. Then, we call the filter()
method. This method is an intermediate operation that returns a stream with elements that is selected by the specified functionality in the method argument.
Then, we call the
sorted()
method. This method is a stateful intermediate operation that returns a stream that consists of sorted elements from the current stream. The sort order is according to the natural ordering of elements.
Lastly, we call
toArray()
method. This method is a terminal operation that returns an Object-type array that consists of elements of the current stream. In addition to Stream, which is a stream of object references, there are primitive specializations for IntStream, LongStream, and DoubleStream. These types of streams have operations that don't exist in the Stream class.
If we want a stream that runs in parallel, we use the
parallelStream()
method. This method returns a possibly parallel Stream with its source. It is allowable for this method to return a sequential stream. This method implements parallelism. Thus, this method benefits from multicore systems. When processing large arrays, parallel computing can improve the performance.
import java.util.stream.Stream; import java.util.Arrays; import java.util.List; public class SampleClass{ public static void main(String[] args){ List<String> list = Arrays.asList("Apple","Carrot", "Mango","Melon"); StringBuilder sb = list.parallelStream() .collect(StringBuilder::new, (i,j) -> i.append("-"+j+"-"), (x,y) -> x.append("|").append(y)); System.out.println(sb.toString()); } } Result -Apple-|-Carrot-|-Mango-|-Melon-This is the form of
collect()
method that I used in the example above:<R> R collect(Supplier<R> supplier, BiConsumer<R,? super T> accumulator, BiConsumer<R,R> combiner)This method performs a mutable reduction operation on the elements of this stream. A mutable reduction is one in which the reduced value is a mutable result container(such as an ArrayList and StringBuilder) and elements are incorporated by updating the state of the result rather than by replacing the result. In Stream, Reduction simply means accumulating data and combining them as one.
Like
reduce(Object, BinaryOperator)
, collect operations can be parallelized without requiring additional synchronization. This is a terminal operation.
The first parameter is a Supplier type. Stream initializes multiple instances of this parameter to hold the elements that we're gonna accumulate in the source. The second parameter is a BiConsumer type. This parameter accepts a lambda expression that supplies suppliers with elements of the source. The third parameter is also a BiConsumer type. This parameter concatenates results from multiple accumulators that run in parallel.
I'll demonstrate some methods of Stream class in this tutorial. More methods can be seen in the documentation.
allMatch() Method
Method form:
boolean allMatch(Predicate<? super T> predicate)
Returns whether all elements of this stream match the provided predicate. May not evaluate the predicate on all elements if not necessary for determining the result. If the stream is empty then true is returned and the predicate is not evaluated. This is a short-circuiting terminal operation.
import java.util.stream.Stream; import java.util.ArrayList; public class SampleClass{ public static void main(String[] args){ ArrayList<Integer> ar = new ArrayList<>(); ar.add(2); ar.add(4); ar.add(6); ar.add(8); ar.add(10); boolean result = ar.stream() .allMatch(i -> (i % 2) == 0); System.out.println("All numbers divisible by 2?"); System.out.println(result); } } All numbers divisible by 2? true
anyMatch() Method
Method form:
boolean anyMatch(Predicate>? super T> predicate)
Returns whether any elements of this stream match the provided predicate. May not evaluate the predicate on all elements if not necessary for determining the result. If the stream is empty then false is returned and the predicate is not evaluated. This is a short-circuiting terminal operation.
import java.util.stream.Stream; import java.util.ArrayList; public class SampleClass{ public static void main(String[] args){ ArrayList<Integer> ar = new ArrayList<>(); ar.add(3); ar.add(4); ar.add(7); ar.add(9); ar.add(17); boolean result = ar.stream() .anyMatch(i -> (i % 2) == 0); System.out.println("Any number divisible by 2?"); System.out.println(result); } } Result Any number divisible by 2? true
builder() Method
Returns a String.Builder object for a Stream.
String.Builder
is a mutable builder for a Stream. This allows the creation of a Stream by generating elements individually and adding them to the Builder (without the copying overhead that comes from using an ArrayList as a temporary buffer. We can use this builder if we want to generate elements without external source.
import java.util.stream.Stream; import java.util.ArrayList; public class SampleClass{ public static void main(String[] args){ ArrayList<Object> ar = new ArrayList<>( Stream.builder().add(2).add(4) .add(6).add(8) .build().toList()); System.out.println("Squared numbers..."); for(int i = 0; i < ar.size(); i++){ int num = (Integer)ar.get(i); System.out.print((num * num) + " "); } } } Result Squared numbers... 4 16 36 64
collect() Method
This method has two forms. One of its forms has been explained in the first topic. In this topic, I'm gonna demonstrate this form.
Method form:
<R, A> R collect(Collector<? super T,A,R> collector)
This method performs a mutable reduction operation on the elements of this stream using a Collector. A Collector encapsulates the functions used as arguments to
collect(Supplier, BiConsumer, BiConsumer)
, allowing for reuse of collection strategies and composition of collect operations such as multiple-level grouping or partitioning.
If the stream is parallel, and the Collector is concurrent, and either the stream is unordered or the collector is unordered, then a concurrent reduction will be performed (see Collector for details on concurrent reduction.) This is a terminal operation.
When executed in parallel, multiple intermediate results may be instantiated, populated, and merged so as to maintain isolation of mutable data structures. Therefore, even when executed in parallel with non-thread-safe data structures (such as ArrayList), no additional synchronization is needed for a parallel reduction.
import java.util.stream.Stream; import java.util.stream.Collectors; import java.util.ArrayList; public class SampleClass{ public static void main(String[] args){ ArrayList<String> ar = new ArrayList<>(); ar.add("The"); ar.add("Big"); ar.add("Brown"); ar.add("Fox"); String result = ar.stream().collect(Collectors.joining(" ")); System.out.println(result); } } Result The Big Brown FoxIn the example above, we call
collect()
method with Collectors.joining()
method in the argument. Collectors interface has lots of useful static methods that return a Collector. joining(CharSeqience delimiter)
method returns a Collector that concatenates the input elements, separated by the specified delimiter, in encounter order.
concat() Method
Method form:
static <T> Stream<T> concat(Stream<? extends T> a,Stream<? extends T> b)
Creates a lazily concatenated stream whose elements are all the elements of the first stream followed by all the elements of the second stream. The resulting stream is ordered if both of the input streams are ordered, and parallel if either of the input streams is parallel. When the resulting stream is closed, the close handlers for both input streams are invoked.
This method operates on the two input streams and binds each stream to its source. As a result subsequent modifications to an input stream source may not be reflected in the concatenated stream result.
import java.util.stream.Stream; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class SampleClass{ public static void main(String[] args){ ArrayList<String> ar1 = new ArrayList<>(); Collections.addAll(ar1,"A","B","C","D"); ArrayList<String> ar2 = new ArrayList<>(); Collections.addAll(ar2,"E","F","G","H"); List<String> list = Stream.concat(ar1.stream(), ar2.stream()) .toList(); System.out.println("Elements..."); for(String str : list) System.out.print(str + " "); } } Result A B C D E F G H
count() Method
This method returns the count of elements in this stream. This is a special case of a reduction and is equivalent to:
return mapToLong(e -> 1L).sum();
This is a terminal operation.
import java.util.stream.Stream; import java.util.stream.Collectors; import java.util.ArrayList; public class SampleClass{ public static void main(String[] args){ ArrayList<String> ar = new ArrayList<>(); ar.add("The"); ar.add("Big"); ar.add("Brown"); ar.add("Fox"); long count = ar.stream().count(); System.out.println(count); } } Result 4
distinct() Method
Returns a stream consisting of the distinct elements (according to
Object.equals(Object)
) of this stream.For ordered streams, the selection of distinct elements is stable (for duplicated elements, the element appearing first in the encounter order is preserved.) For unordered streams, no stability guarantees are made. This is a stateful intermediate operation.
import java.util.stream.Stream; import java.util.ArrayList; import java.util.List; public class SampleClass{ public static void main(String[] args){ ArrayList<String> ar = new ArrayList<>(); ar.add("Apple"); ar.add("Melon"); ar.add("Apple"); ar.add("Avocado"); ar.add("Watermelon"); ar.add("Avocado"); List<String> list = ar.stream().distinct().toList(); System.out.println("Elements..."); for(String str : list) System.out.print(str + " "); } } Result Elements... Apple Melon Avocado Watermelon
dropWhile() Method
Method form:
efault Stream<T> dropWhile(Predicate<? super T> predicate)
Returns, if this stream is ordered, a stream consisting of the remaining elements of this stream after dropping the longest prefix of elements that match the given predicate. Otherwise returns, if this stream is unordered, a stream consisting of the remaining elements of this stream after dropping a subset of elements that match the given predicate.
If this stream is ordered then the longest prefix is a contiguous sequence of elements of this stream that match the given predicate. The first element of the sequence is the first element of this stream, and the element immediately following the last element of the sequence does not match the given predicate.
If this stream is unordered, and some (but not all) elements of this stream match the given predicate, then the behavior of this operation is nondeterministic; it is free to drop any subset of matching elements (which includes the empty set).
Independent of whether this stream is ordered or unordered if all elements of this stream match the given predicate then this operation drops all elements (the result is an empty stream), or if no elements of the stream match the given predicate then no elements are dropped (the result is the same as the input). This is a stateful intermediate operation.
Streams may or may not have a defined encounter order. Whether or not a stream has an encounter order depends on the source and the intermediate operations. Certain stream sources (such as List or arrays) are intrinsically ordered, whereas others (such as HashSet) are not. Some intermediate operations, such as sorted(), may impose an encounter order on an otherwise unordered stream, and others may render an ordered stream unordered.
import java.util.stream.Stream; import java.util.Arrays; import java.util.List; public class SampleClass{ public static void main(String[] args){ String[] ar = {"Apple", "Melon", "Avocado", "Watermelon","Avocado"}; List<String> list = Arrays.stream(ar) .dropWhile(x -> !x.equals("Avocado")) .toList(); System.out.println("Elements..."); for(String str : list) System.out.print(str + " "); } } Result Elements... Avocado Watermelon AvocadoIn the example above, we see that as long as the return value of predicate in
dropWhile()
is true, evaluated elements that is evaluated as true will be dropped. If the return value of predicate in dropWhile()
is false, the evaluated element that is evaluated as false and the subsequent elements will be included in the Stream that will be returned by dropWhile()
.
filter() Method
Method form:
Stream<T> filter(Predicate<? super T> predicate)
Returns a stream consisting of the elements of this stream that match the given predicate.
import java.util.stream.Stream; import java.util.ArrayList; public class SampleClass{ public static void main(String[] args){ ArrayList<String> ar = new ArrayList<>(); ar.add("Apple"); ar.add("Melon"); ar.add("Mango"); ar.add("Avocado"); ar.add("Watermelon"); ar.add("Mangosteen"); Object[] subFruits = ar.stream() .filter(f -> f.startsWith("M")) .sorted().toArray(); System.out.println("Fruits that start " +"with \"M\""); for(Object obj : subFruits) System.out.println(obj); } } Result Fruits that start with "M" Mango Mangosteen Melon
findAny() Method
Method form:
Optional<T> findAny()
Returns an Optional describing some element of the stream, or an empty Optional if the stream is empty. This is a short-circuiting terminal operation.
The behavior of this operation is explicitly nondeterministic; it is free to select any element in the stream. This is to allow for maximal performance in parallel operations; the cost is that multiple invocations on the same source may not return the same result. (If a stable result is desired, use
findFirst()
instead.)
import java.util.stream.Stream; import java.util.ArrayList; public class SampleClass{ public static void main(String[] args){ ArrayList<String> ar = new ArrayList<>(); ar.add("Apple"); ar.add("Melon"); ar.add("Watermelon"); ar.add("Avocado"); String result = ar.stream().findAny().get(); System.out.println(result); } }
findFirst() Method
Returns an Optional describing the first element of this stream, or an empty Optional if the stream is empty. If the stream has no encounter order, then any element may be returned. This is a short-circuiting terminal operation.
import java.util.stream.Stream; import java.util.ArrayList; public class SampleClass{ public static void main(String[] args){ ArrayList<String> ar = new ArrayList<>(); ar.add("Apple"); ar.add("Melon"); ar.add("Watermelon"); ar.add("Avocado"); String result = ar.stream().findFirst().get(); System.out.println(result); } } Result Apple
flatMap() Method
Method form:
<R> Stream<R> flatMap(Function<? super T,? extends Stream<? extends R>> mapper)
Returns a stream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element. Each mapped stream is closed after its contents have been placed into this stream. (If a mapped stream is null an empty stream is used, instead.) This is an This is a intermediate operation.
import java.util.stream.Stream; import java.util.Arrays; public class SampleClass{ public static void main(String[] args){ Integer[][] ints = {{2,4,6},{3,7,9}}; Object[] flatInts = Arrays.stream(ints) .flatMap(l -> Arrays.stream(l)) .toArray(); System.out.println("Flattened array of " +"integers."); for(Object o : flatInts) System.out.print(o + " "); } } Result Flattened array of integers. 2 4 6 3 7 9In the example above, we are able to convert two-dimensional array into a one-dimensional array. In other words, we are able to flatten a two-dimensional array.
Flattening is a process of merging several layers into one single layer. When we flatten an array(or collection), we get all elements from arrays within the array and merge all elements in a one-dimensional array.
Here's another example. This time, we're gonna modify the mapped values.
import java.util.stream.Stream; import java.util.Arrays; public class SampleClass{ public static void main(String[] args){ Integer[][] ints = {{2,4,6},{3,7,9}}; Object[] flatInts = Arrays.stream(ints) .flatMap(l -> Arrays.stream(l)) .map(v -> v*v) .toArray(); System.out.println("Flattened array of " +"integers."); for(Object o : flatInts) System.out.print(o + " "); } } Result Flattened array of integers. 4 16 36 9 49 81In the example above, we use
flatMap()
to map elements and put them in a flattened container. Then, we use map()
to map elements in the flattened container and square them. Then, toArray()
converts the flattened container into an Object-type array.
Mapping is a process of associating an element from a set to another set. Association of elements could be copying an element to another set, generating new elements from elements in the set, etc.
There are methods that are associated with
flatMap()
. These are: flatMapToDouble(), flatMapToInt() and flatMapToLong(). These methods don't return Stream. They return DoubleStream, IntStream and LongStream respectively. These versions of Stream are specialized in primitive wrapper classes.
This example demonstrates
flatMapToInt()
method.
import java.util.stream.Stream; import java.util.stream.IntStream; import java.util.Arrays; public class SampleClass{ public static void main(String[] args){ Integer[][] ints = {{2,4,6},{3,7,9}}; int sum = Arrays.stream(ints) .flatMapToInt(n -> Arrays.stream(n) .mapToInt(m -> m)) .sum(); System.out.println("sum: " + sum); } }In the example above, we get a Stream instance from
ints
. Then, we use flatMapToInt()
. This method returns IntStream. Thus, the elements in the flattened container need to be placed in an IntStream. To achieve that, we use mapToInt()
method. This method map every element in the flattened container and wrap them into IntStream. Then, we use sum()
method. This method returns an int
that is the sum of all elements in IntStream.
forEach() Method
Method form:
void forEach(Consumer<? super T> action)
Performs an action for each element of this stream. This is a terminal operation. The behavior of this operation is explicitly nondeterministic. For parallel stream pipelines, this operation does not guarantee to respect the encounter order of the stream, as doing so would sacrifice the benefit of parallelism.
For any given element, the action may be performed at whatever time and in whatever thread the library chooses. If the action accesses shared state, it is responsible for providing the required synchronization.
import java.util.stream.Stream; import java.util.ArrayList; public class SampleClass{ public static void main(String[] args){ ArrayList<String> ar = new ArrayList<>(); ar.add("Apple"); ar.add("Melon"); ar.add("Watermelon"); ar.add("Avocado"); ar.stream().forEach(System.out::println); } }
forEachOrdered() Method
Performs an action for each element of this stream, in the encounter order of the stream if the stream has a defined encounter order. This is a terminal operation. This operation processes the elements one at a time, in encounter order if one exists.
Performing the action for one element happens-before performing the action for subsequent elements, but for any given element, the action may be performed in whatever thread the library chooses. In multithreading,
forEachOrdered()
is more predictable than forEach()
. Also, forEachOrdered()
follows defined encounter order of a collection and array.
import java.util.stream.Stream; import java.util.ArrayList; public class SampleClass{ public static void main(String[] args){ ArrayList<String> ar = new ArrayList<>(); ar.add("Apple"); ar.add("Melon"); ar.add("Watermelon"); ar.add("Avocado"); ar.stream().forEachOrdered(System.out::println); } } Result Apple Melon Watermelon Avocado
generate() Method
Method form:
static <T> Stream<T> generate(Supplier<? extends T> s)
Returns an infinite sequential unordered stream where each element is generated by the provided Supplier. This is suitable for generating constant streams, streams of random elements, etc.
This example demonstrate
generate()
method. This example will infinitely run. You need to stop your IDE or command prompt(if you're using windows) by force to end the execution.
import java.util.stream.Stream; public class SampleClass{ public static void main(String[] args){ Stream.generate(() -> "Hello") .forEach(System.out::println); } }We use the
limit()
to put a limit on an infinite stream like generate()
.
import java.util.stream.Stream; import java.util.Random; public class SampleClass{ public static void main(String[] args){ Object[] num = Stream.generate(() -> new Random() .nextInt(150)) .limit(10) .toArray(); for(Object o : num) System.out.print(o + " "); } }
iterate() Method
This method has two forms. Let's start with this form:
Method form:
static <T> Stream<T> iterate(T seed,
Predicate<? super T> hasNext,
UnaryOperator<T> next)
This method returns a sequential ordered Stream produced by iterative application of the given next function to an initial element, conditioned on satisfying the given hasNext predicate. The stream terminates as soon as the hasNext predicate returns false.
The resulting sequence may be empty if the hasNext predicate does not hold on the seed value. Otherwise the first element will be the supplied seed value, the next element (if present) will be the result of applying the next function to the seed value, and so on iteratively until the hasNext predicate indicates that the stream should terminate.
The action of applying the hasNext predicate to an element happens-before the action of applying the next function to that element. The action of applying the next function for one element happens-before the action of applying the hasNext predicate for subsequent elements. For any given element an action may be performed in whatever thread the library chooses.
import java.util.stream.Stream; public class SampleClass{ public static void main(String[] args){ Object[] num = Stream.iterate(0, i -> i < 1000, i -> (++i)*i) .toArray(); for(Object o : num) System.out.print(o + " "); } } Result 0 1 4 25 676Next, let's discuss the next form:
static <T> Stream<T> iterate(T seed, UnaryOperator<T> f)
This method returns an infinite sequential ordered Stream produced by iterative application of a function f to an initial element seed, producing a Stream consisting of seed, f(seed), f(f(seed)), etc. The first element (position 0) in the Stream will be the provided seed. For n > 0, the element at position n, will be the result of applying the function f to the element at position n - 1.
The action of applying f for one element happens-before the action of applying f for subsequent elements. For any given element the action may be performed in whatever thread the library chooses.
import java.util.stream.Stream; public class SampleClass{ public static void main(String[] args){ Object[] num = Stream.iterate(0, i -> (++i)*i) .limit(6) .toArray(); for(Object o : num) System.out.print(o + " "); } } Result 0 1 4 25 676 458329We use the
limit()
to put a limit on the infinite stream.
map() Method
Method form:
<R> Stream<R> map(Function<? super T,? extends R> mapper)
Returns a stream consisting of the results of applying the given function to the elements of this stream. This is an intermediate operation.
import java.util.stream.Stream; import java.util.Arrays; public class SampleClass{ public static void main(String[] args){ Integer[] ints = {2,4,6,3,7,9}; Object[] mappedInts = Arrays.stream(ints) .map(v -> v*v) .toArray(); System.out.println("Array of " +"integers."); for(Object o : mappedInts) System.out.print(o + " "); } } Result Array of integers. 4 16 36 9 49 81There are methods that are associated with
map()
. These are: mapToDouble(), mapToInt() and mapToLong(). These methods don't return Stream. They return DoubleStream, IntStream and LongStream respectively. These versions of Stream are specialized in primitive wrapper classes.
This example demonstrates
mapToInt()
method.
import java.util.stream.Stream; import java.util.Arrays; public class SampleClass{ public static void main(String[] args){ Integer[] ints = {2,4,6,3,7,9}; int sum = Arrays.stream(ints) .mapToInt(v -> v*v) .sum(); System.out.println("Sum: " + sum); } } Result Sum: 195In the example above, we use
sum()
method. This method returns an int
that is the sum of all mapped elements in IntStream.
Mapping is a process of associating an element from a set to another set. Association of elements could be copying an element to another set, generating new elements from elements in the set, etc.
mapMulti() Method
Method form:
default <R> Stream<R> mapMulti(BiConsumer<? super T,? super Consumer<R>> mapper)
Returns a stream consisting of the results of replacing each element of this stream with multiple elements, specifically zero or more elements. Replacement is performed by applying the provided mapping function to each element in conjunction with a consumer argument that accepts replacement elements. The mapping function calls the consumer zero or more times to provide the replacement elements.
This is an intermediate operation. If the consumer argument is used outside the scope of its application to the mapping function, the results are undefined. This method is similar to flatMap in that it applies a one-to-many transformation to the elements of the stream and flattens the result elements into a new stream.
import java.util.stream.Stream; import java.util.Arrays; public class SampleClass{ public static void main(String[] args){ Integer[][] ints = {{2,4,6},{3,7,9}}; Object[] flatInts = Arrays.stream(ints) .<Integer>mapMulti( (container, consumer) -> { for(Integer i : container) consumer.accept(i*i); }) .toArray(); System.out.println("Flattened array of " +"integers."); for(Object o : flatInts) System.out.print(o + " "); } } Result Flattened array of integers. 4 16 36 9 49 81In the example above, we flatten and map elements without opening additional Stream and additional
map
operation. We feed the mapped elements to the consumer and the consumer put those elements in a Stream with flattened container. The <Integer>
before mapMulti()
is an additional type information. According to the documentation:If a lambda expression is provided as the mapper function argument, additional type information may be necessary for proper inference of the element type <R> of the returned stream. This can be provided in the form of explicit type declarations for the lambda parameters or as an explicit type argument to the mapMulti call.
This is how we achieve the result above using
flatMap()
.
import java.util.stream.Stream; import java.util.Arrays; public class SampleClass{ public static void main(String[] args){ Integer[][] ints = {{2,4,6},{3,7,9}}; Object[] flatInts = Arrays.stream(ints) .flatMap(l -> Arrays.stream(l)) .map(v -> v*v) .toArray(); System.out.println("Flattened array of " +"integers."); for(Object o : flatInts) System.out.print(o + " "); } }As we can see, on top of
Arrays.stream(ints)
, we add another stream in flatMap()
and another intermediate operation which is map()
.
There are methods that are associated with
mapMulti()
. These are: mapMultiToDouble(), mapMultiToInt() and mapMultiToLong(). These methods don't return Stream. They return DoubleStream, IntStream and LongStream respectively. These versions of Stream are specialized in primitive wrapper classes.
This example demonstrates
mapMultiToInt()
method.
import java.util.stream.Stream; import java.util.stream.IntStream; import java.util.Arrays; public class SampleClass{ public static void main(String[] args){ Integer[][] ints = {{2,4,6},{3,7,9}}; int sum = Arrays.stream(ints) .<Integer>mapMultiToInt( (container, consumer) -> { for(Integer i : container) consumer.accept(i*i); }) .sum(); System.out.println("Sum: " + sum); } } Result Sum: 195
mapMulti()
is preferable to flatMap()
in the following circumstances:
- When replacing each stream element with a small (possibly zero) number of elements. Using this method avoids the overhead of creating a new Stream instance for every group of result elements, as required by flatMap.
- When it is easier to use an imperative approach for generating result elements than it is to return them in the form of a Stream.
max() Method
Method form:
Optional<T> max(Comparator<? super T> comparator)
This method is a terminal operation that performs a reduction that specializes in finding the maximum element of the stream according to the provided Comparator. This method returns an Optional<T> object.
import java.util.stream.Stream; import java.util.ArrayList; import java.util.List; public class SampleClass{ public static void main(String[] args){ ArrayList<String> ar = new ArrayList<>(); ar.add("Apple"); ar.add("melon"); ar.add("Watermelon"); ar.add("avocado"); String max = ar.stream() .max(String.CASE_INSENSITIVE_ORDER) .get(); System.out.println("Max value: " + max); } } Result Max value: Watermelon
min() Method
Method form:
Optional<T> min(Comparator<? super T> comparator)
This method is a terminal operation that performs a reduction that specializes in finding the minimum element of the stream according to the provided Comparator. This method returns an Optional<T> object.
import java.util.stream.Stream; import java.util.ArrayList; import java.util.List; public class SampleClass{ public static void main(String[] args){ ArrayList<String> ar = new ArrayList<>(); ar.add("Apple"); ar.add("melon"); ar.add("Watermelon"); ar.add("avocado"); String min = ar.stream() .min(String.CASE_INSENSITIVE_ORDER) .get(); System.out.println("Min value: " + min); } } Result Min value: Apple
noneMatch() Method
Method form:
boolean noneMatch(Predicate<? super T> predicate)
Returns whether no elements of this stream match the provided predicate. May not evaluate the predicate on all elements if not necessary for determining the result. If the stream is empty then true is returned and the predicate is not evaluated. This is a short-circuiting terminal operation.
import java.util.stream.Stream; import java.util.ArrayList; public class SampleClass{ public static void main(String[] args){ ArrayList<Integer> ar = new ArrayList<>(); ar.add(3); ar.add(7); ar.add(13); ar.add(9); ar.add(17); boolean result = ar.stream() .noneMatch(i -> (i % 2) == 0); System.out.println("No number divisible by 2?"); System.out.println(result); } } Result No number divisible by 2? true
of() Method
This method has two forms.
static <T> Stream<T> of(T t)
returns a sequential Stream containing a single element.static <T> Stream<T> of(T... values)
returns a sequential ordered stream whose elements are the specified values.This example demonstrates
of(T... values)
method.
import java.util.stream.Stream; public class SampleClass{ public static void main(String[] args){ Stream.of("Apple", "Melon", "Avocado", "Watermelon","Avocado") .dropWhile(x -> !x.equals("Avocado")) .forEach(System.out::println); } } Result Avocado Watermelon AvocadoThis example demonstrates
of(T t)
method.
import java.util.stream.Stream; public class SampleClass{ public static void main(String[] args){ Stream.of(new String[]{ "Apple", "Melon", "Avocado", "Watermelon","Avocado"}) .filter(f -> f.startsWith("A")) .forEach(System.out::println); } } Result Apple Avocado Avocado
ofNullable() Method
Method form:
static <T> Stream<T> ofNullable(T t)
Returns a sequential Stream containing a single element, if non-null, otherwise returns an empty Stream.
import java.util.stream.Stream; public class SampleClass{ public static void main(String[] args){ long count = Stream.ofNullable(null). count(); //this will throw an error //long count = Stream.of(null).count(); System.out.println("Count: " + count); } }
peek() Method
Method form:
Stream<T> peek(Consumer<? super T> action)
Returns a stream consisting of the elements of this stream, additionally performing the provided action on each element as elements are consumed from the resulting stream. This is an intermediate operation.
For parallel stream pipelines, the action may be called at whatever time and in whatever thread the element is made available by the upstream operation. If the action modifies shared state, it is responsible for providing the required synchronization.
This method exists mainly to support debugging, where you want to see the elements as they flow past a certain point in a pipeline:
import java.util.stream.Stream; import java.util.List; import java.util.stream.Collectors; public class SampleClass{ public static void main(String[] args){ List<String> list = Stream.of("one", "two", "three", "four") .filter(e -> e.length() > 3) .peek(e -> System.out.println("Filtered value: " + e)) .map(String::toUpperCase) .peek(e -> System.out.println("Mapped value: " + e)) .collect(Collectors.toList()); System.out.println("List elements..."); for(String str : list) System.out.println(str); } } Result Filtered value: three Mapped value: THREE Filtered value: four Mapped value: FOUR List elements... THREE FOURIn cases where the stream implementation is able to optimize away the production of some or all the elements (such as with short-circuiting operations like findFirst, or in the example described in count()), the action will not be invoked for those elements.
reduce() Method
This method has three forms. Let's start with this form:
Optional<T> reduce(BinaryOperator<T> accumulator)
This terminal operation performs a reduction on the elements of this stream, using an associative accumulation function, and returns an Optional describing the reduced value, if any. The accumulator function must be an associative function. Reduction operations can be parallelized without requiring additional synchronization.
import java.util.stream.Stream; import java.util.ArrayList; public class SampleClass{ public static void main(String[] args){ ArrayList<Integer> ar = new ArrayList<>(); ar.add(2); ar.add(4); ar.add(6); ar.add(184); int result = ar.stream() .reduce( (curr,next) -> curr*next) .get(); System.out.println(result); } } Result 8832Next, let's discuss this form:
T reduce(T identity, BinaryOperator<T> accumulator)
import java.util.stream.Stream; import java.util.ArrayList; public class SampleClass{ public static void main(String[] args){ ArrayList<Integer> ar = new ArrayList<>(); ar.add(4); ar.add(6); ar.add(184); int result = ar.stream() .reduce(Integer.valueOf(2), (curr,next) -> curr*next); System.out.println(result); } } Result 8832In the example above,
identity
is the initial value which is 2. identity
is also the default result if the stream is empty. Unlike in the first form, this form doesn't return Optional object.
Next, let's discuss the last form:
<U> U reduce(U identity, BiFunction<U,? super T,U> accumulator, BinaryOperator<U> combiner)
import java.util.stream.Stream; import java.util.ArrayList; public class SampleClass{ public static void main(String[] args){ ArrayList<Integer> ar = new ArrayList<>(); ar.add(4); ar.add(6); ar.add(184); int result = ar.parallelStream() .reduce(Integer.valueOf(2), (x,y) -> x*y, (i,j) -> i+j); System.out.println(result); } } Result 8832In the example above,
identity
is the initial value and default result if the stream is empty. accumulator
is a function that multiplies two numbers. combiner
combines results from multiple accumulators. The combiner function must be an associative function.
Take note, use
parallelStream()
if you're processing large arrays in order to take advantage of parallelism. This example is just a mere demonstration of reduce()
.
skip() Method
Method form:
Stream<T> skip(long n)
Returns a stream consisting of the remaining elements of this stream after discarding the first n elements of the stream. If this stream contains fewer than n elements then an empty stream will be returned. This is a stateful intermediate operation.
import java.util.stream.Stream; import java.util.ArrayList; public class SampleClass{ public static void main(String[] args){ ArrayList<Integer> ar = new ArrayList<>(); ar.add(2); ar.add(4); ar.add(6); ar.add(8); ar.add(10); ar.add(12); ar.stream() .skip(3) .forEach(System.out::println); } } Result 8 10 12
takeWhile() Method
Returns, if this stream is ordered, a stream consisting of the longest prefix of elements taken from this stream that match the given predicate. Otherwise returns, if this stream is unordered, a stream consisting of a subset of elements taken from this stream that match the given predicate.
If this stream is ordered then the longest prefix is a contiguous sequence of elements of this stream that match the given predicate. The first element of the sequence is the first element of this stream, and the element immediately following the last element of the sequence does not match the given predicate.
If this stream is unordered, and some (but not all) elements of this stream match the given predicate, then the behavior of this operation is nondeterministic; it is free to take any subset of matching elements (which includes the empty set).
Independent of whether this stream is ordered or unordered if all elements of this stream match the given predicate then this operation takes all elements (the result is the same as the input), or if no elements of the stream match the given predicate then no elements are taken (the result is an empty stream). This is a short-circuiting stateful intermediate operation.
import java.util.stream.Stream; import java.util.Arrays; import java.util.List; public class SampleClass{ public static void main(String[] args){ String[] ar = {"Apple", "Melon", "Avocado", "Watermelon","Avocado"}; List<String> list = Arrays.stream(ar) .takeWhile(x -> !x.equals("Avocado")) .toList(); System.out.println("Elements..."); for(String str : list) System.out.print(str + " "); } } Result Elements... Apple MelonIn the example above, we see that as long as the return value of predicate in
takeWhile()
is true, evaluated elements that is evaluated as true will be included in the Stream that will be returned by takeWhile()
. If the return value of predicate in takeWhile()
is false, the evaluated element that is evaluated as false and the subsequent elements will be dropped.
No comments:
Post a Comment