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 : The behavior of this operation is explicitly nondeterministic. Also, for any given element, the action may be performed at whatever time and in whatever thread the library chooses.
Example 1 : To perform print operation on each element of reversely sorted stream.
import java.util.*;
class GFG {
public static void main(String[] args)
{
List<Integer> list = Arrays.asList( 2 , 4 , 6 , 8 , 10 );
list.stream().sorted(Comparator.reverseOrder()).forEach(System.out::println);
}
}
|
Example 2 : To perform print operation on each element of string stream.
import java.util.*;
class GFG {
public static void main(String[] args)
{
List<String> list = Arrays.asList( "GFG" , "Geeks" ,
"for" , "GeeksforGeeks" );
list.stream().forEach(System.out::println);
}
}
|
Output:
GFG
Geeks
for
GeeksforGeeks
Example 3 : To perform print operation on each element of reversely sorted string stream.
import java.util.*;
import java.util.stream.Stream;
class GFG {
public static void main(String[] args)
{
Stream<String> stream = Stream.of( "GFG" , "Geeks" ,
"for" , "GeeksforGeeks" );
stream.sorted(Comparator.reverseOrder())
.flatMap(str -> Stream.of(str.charAt( 1 )))
.forEach(System.out::println);
}
}
|