The Wayback Machine - https://web.archive.org/web/20241001103514/https://www.geeksforgeeks.org/stream-foreachordered-method-java-examples/
Open In App

Stream forEachOrdered() method in Java with examples

Last Updated : 06 Dec, 2018
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Stream forEachOrdered(Consumer action) performs an action for each element of this stream, in the encounter order of the stream if the stream has a defined encounter order. Stream forEachOrdered(Consumer action) is a terminal operation i.e, it may traverse the stream to produce a result or a side-effect.

Syntax :

void forEachOrdered(Consumer<? super T> action)

Where, Consumer is a functional interface which 
is expected to operate via side-effects. and T 
is the type of stream elements.

Note : 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.

Example 1 : To print the elements of integer array in original order.




// Java code for forEachOrdered
// (Consumer action) in Java 8
import java.util.*;
  
class GFG {
      
    // Driver code
    public static void main(String[] args) {
  
    // Creating a list of Integers
    List<Integer> list = Arrays.asList(10, 19, 20, 1, 2);
      
    // Using forEachOrdered(Consumer action) to 
    // print the elements of stream in encounter order
    list.stream().forEachOrdered(System.out::println);
      
  
}
}


Output:

10
19
20
1
2

Example 2 : To print the elements of string array in original order.




// Java code for forEachOrdered
// (Consumer action) in Java 8
import java.util.*;
  
class GFG {
      
    // Driver code
    public static void main(String[] args) {
  
    // Creating a list of Strings
    List<String> list = Arrays.asList("GFG", "Geeks"
                             "for", "GeeksforGeeks");
      
    // Using forEachOrdered(Consumer action) to 
    // print the elements of stream in encounter order
    list.stream().forEachOrdered(System.out::println);
      
  
}
}


Output:

GFG
Geeks
for
GeeksforGeeks

Example 3 : To print the characters at index 2 of string array in original order.




// Java code for forEachOrdered
// (Consumer action) in Java 8
import java.util.*;
import java.util.stream.Stream;
  
  
class GFG {
      
    // Driver code
    public static void main(String[] args) {
  
    // Creating a Stream of Strings
    Stream<String> stream = Stream.of("GFG", "Geeks"
                             "for", "GeeksforGeeks");
      
    // Using forEachOrdered(Consumer action) 
    stream.flatMap(str-> Stream.of(str.charAt(2)))
          .forEachOrdered(System.out::println);
      
  
}
}


Output:

G
e
r
e


Previous Article
Next Article

Similar Reads

IntStream forEachOrdered() method in Java
IntStream forEachOrdered(IntConsumer action) performs an action for each element of this stream in encounter order. IntStream forEachOrdered(IntConsumer action) is a terminal operation i.e, it may traverse the stream to produce a result or a side-effect. Syntax : void forEachOrdered(IntConsumer action) Parameter : IntConsumer represents an operatio
2 min read
DoubleStream forEachOrdered() method in Java
DoubleStream forEachOrdered(DoubleConsumer action) performs an action for each element of this stream in encounter order. DoubleStream forEachOrdered(DoubleConsumer action) is a terminal operation i.e, it may traverse the stream to produce a result or a side-effect. Syntax : void forEachOrdered(DoubleConsumer action) Parameter : DoubleConsumer repr
2 min read
LongStream forEachOrdered() method in Java
LongStream forEachOrdered(LongConsumer action) performs an action for each element of this stream in encounter order. LongStream forEachOrdered(LongConsumer action) is a terminal operation i.e, it may traverse the stream to produce a result or a side-effect. Syntax : void forEachOrdered(LongConsumer action) Parameter : LongConsumer represents an op
2 min read
Difference between Stream.of() and Arrays.stream() method in Java
Arrays.stream() The stream(T[] array) method of Arrays class in Java, is used to get a Sequential Stream from the array passed as the parameter with its elements. It returns a sequential Stream with the elements of the array, passed as parameter, as its source. Example: Java Code // Java program to demonstrate Arrays.stream() method import java.uti
5 min read
Character Stream Vs Byte Stream in Java
A stream is a sequence of data. I/O Stream refers to a stream that is unlikely a method to sequentially access a file. I/O Stream means an input source or output destination representing different types of sources e.g. disk files. The java.io package provides classes that allow you to convert between Unicode character streams and byte streams of no
4 min read
foreach() loop vs Stream foreach() vs Parallel Stream foreach()
foreach() loopLambda operator is not used: foreach loop in Java doesn't use any lambda operations and thus operations can be applied on any value outside of the list that we are using for iteration in the foreach loop. The foreach loop is concerned over iterating the collection or array by storing each element of the list on a local variable and do
4 min read
Stream skip() method in Java with examples
Prerequisite : Streams in java The skip(long N) is a method of java.util.stream.Stream object. This method takes one long (N) as an argument and returns a stream after removing first N elements. skip() can be quite expensive on ordered parallel pipelines, if the value of N is large, because skip(N) is constrained to skip the first N elements in the
3 min read
Stream.max() method in Java with Examples
Stream.max() returns the maximum element of the stream based on the provided Comparator. A Comparator is a comparison function, which imposes a total ordering on some collection of objects. max() is a terminal operation which combines stream elements and returns a summary result. So, max() is a special case of reduction. The method returns Optional
3 min read
Stream min() method in Java with Examples
Stream.min() returns the minimum element of the stream based on the provided Comparator. A Comparator is a comparison function, which imposes a total ordering on some collection of objects. min() is a terminal operation which combines stream elements and returns a summary result. So, min() is a special case of reduction. The method returns Optional
2 min read
Stream generate() method in Java with examples
Stream generate(Supplier<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. Syntax : static <T> Stream<T> generate(Supplier<T> s) Where, Stream is an interface and T is the type of s
1 min read
Stream count() method in Java with examples
long count() returns the count of elements in the stream. This is a special case of a reduction (A reduction operation takes a sequence of input elements and combines them into a single summary result by repeated application of a combining operation). This is a terminal operation i.e, it may traverse the stream to produce a result or a side-effect.
2 min read
Stream forEach() method in Java with examples
Stream forEach(Consumer action) performs an action for each element of the stream. Stream forEach(Consumer action) is a terminal operation i.e, it may traverse the stream to produce a result or a side-effect. Syntax : void forEach(Consumer<? super T> action) Where, Consumer is a functional interface and T is the type of stream elements. Note
2 min read
Stream noneMatch() Method in Java with Examples
A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. noneMatch() of Stream class returns whether no elements of this stream match the provided predicate. It may not evaluate the predicate on all elements if not necessary for determining the result. This is a short-circuiting terminal
3 min read
BitSet stream() Method in Java with Examples
The stream() method of Java BitSet class is used to return a stream of indices for every bit contained in the BitSet. The indices are returned in increasing order. The size of the stream is the number of bits in the set state of the BitSet, which is equal to the value returned by the cardinality() method. Syntax: public IntStream stream() Parameter
2 min read
Stream iterate(T,Predicate,UnaryOperator) method in Java with examples
The iterate(T, java.util.function.Predicate, java.util.function.UnaryOperator) method allows us to iterate stream elements till the specified condition. This method returns a sequential ordered Stream produced by iterative application of the given next function to an initial element, conditioned on satisfying hasNext predicate passed as parameter.
2 min read
Stream ofNullable(T) method in Java with examples
The ofNullable(T) method returns a sequential Stream containing a single element if this stream is non-null otherwise method returns an empty Stream. It helps to handle the null stream and NullPointerException. Syntax: static <T> Stream<T> ofNullable(T t) Parameters: This method accepts a single parameter t which is the single element o
2 min read
Stream dropWhile() method in Java with examples
The dropWhile(java.util.function.Predicate) method returns two different types of stream depending upon whether the stream is ordered or not. If the stream is ordered then a stream of the remaining elements of this stream after dropping the longest prefix of elements that match the given predicate is returned by method else a stream consisting of t
3 min read
Stream takeWhile() method in Java with examples
The takeWhile(java.util.function.Predicate) method returns a stream of the remaining elements of this stream after taken the longest prefix of elements that match the given predicate if the stream is ordered else a stream of a subset of elements taken from this stream that match the given predicate. In the case of the ordered stream, the longest pr
3 min read
OptionalLong stream() method in Java with examples
The stream() method help us to get Long value contain by OptionalLong as LongStream.If a value is present, method returns a sequential LongStream containing only that value, otherwise returns an empty LongStream. Syntax: public LongStream stream() Parameters: This method accepts nothing. Return value: This method returns the optional value as an Lo
1 min read
OptionalInt stream() method in Java with examples
The stream() method help us to get value contain by OptionalInt as IntStream. If a value is present, method returns a sequential IntStream containing only that value, otherwise returns an empty IntStream. Syntax: public IntStream stream() Parameters: This method accepts nothing. Return value: This method returns the optional value as an IntStream.
1 min read
OptionalDouble stream() method in Java with examples
The stream() method help us to get double value contain by OptionalDouble as DoubleStream.If a value is present, method returns a sequential DoubleStream containing only that value, otherwise returns an empty DoubleStream. Syntax: public DoubleStream stream() Parameters: This method accepts nothing. Return value: This method returns the optional va
1 min read
Optional stream() method in Java with examples
The stream() method of java.util.Optional class in Java is used to get the sequential stream of the only value present in this Optional instance. If there is no value present in this Optional instance, then this method returns returns an empty Stream. Syntax: public Stream<T> stream() Parameters: This method do not accept any parameter. Retur
2 min read
Stream peek() Method in Java with Examples
In Java, Stream provides an powerful alternative to process data where here we will be discussing one of the very frequently used methods named peek() which being a consumer action basically returns a stream consisting of the elements of this stream, additionally performing the provided action on each element as elements are consumed from the resul
2 min read
Stream.of(T... values) in Java with examples
Stream of(T... values) returns a sequential ordered stream whose elements are the specified values. A sequential stream work just like for-loop using a single core. On the other hand, a Parallel stream divide the provided task into many and run them in different threads, utilizing multiple cores of the computer. Syntax : static <T> Stream<
2 min read
Stream.of(T t) in Java with examples
Stream of(T t) returns a sequential Stream containing a single element i.e, a singleton sequential stream. A sequential stream work just like for-loop using a single core. On the other hand, a Parallel stream divide the provided task into many and run them in different threads, utilizing multiple cores of the computer. Syntax : static <T> Str
2 min read
Stream map() in Java with examples
Stream map(Function mapper) returns a stream consisting of the results of applying the given function to the elements of this stream. Stream map(Function mapper) is an intermediate operation. These operations are always lazy. Intermediate operations are invoked on a Stream instance and after they finish their processing, they give a Stream instance
3 min read
Stream mapToInt() in Java with examples
Stream mapToInt(ToIntFunction mapper) returns an IntStream consisting of the results of applying the given function to the elements of this stream. Stream mapToInt(ToIntFunction mapper) is an intermediate operation. These operations are always lazy. Intermediate operations are invoked on a Stream instance and after they finish their processing, the
2 min read
Stream mapToLong() in Java with examples
Stream mapToLong(ToLongFunction mapper) returns a LongStream consisting of the results of applying the given function to the elements of this stream. Stream mapToLong(ToLongFunction mapper) is an intermediate operation. These operations are always lazy. Intermediate operations are invoked on a Stream instance and after they finish their processing,
2 min read
Stream mapToDouble() in Java with examples
Stream mapToDouble (ToDoubleFunction mapper) returns a DoubleStream consisting of the results of applying the given function to the elements of this stream. Stream mapToDouble (ToDoubleFunction mapper) is an intermediate operation. These operations are always lazy. Intermediate operations are invoked on a Stream instance and after they finish their
2 min read
Stream allMatch() in Java with examples
Stream allMatch(Predicate predicate) returns whether all elements of this stream match the provided predicate. It may not evaluate the predicate on all elements if not necessary for determining the result. This is a short-circuiting terminal operation. A terminal operation is short-circuiting if, when presented with infinite input, it may terminate
3 min read