Home  >  Java 8

Java 8 Stream: forEach, forEachOrdered, peek, skip and toArray Example

By Arvind Rai, November 22, 2014
This page will provide the examples of java 8 Stream forEach, forEachOrdered, peek, skip and toArray methods. Find the details of each method.

Stream.forEach and Stream.forEachOrdered

forEach() method accepts Consumer as an argument and that consumer is applied to each element of the stream. For example we can create a consumer to print the stream element and use it with forEach() method. forEachOrdered() method does the same thing but in the encounter order of the stream.
ForEachDemo.java
package com.concretepage.util.stream;
import java.util.stream.Stream;
public class ForEachDemo {
    public static void main(String[] args) {
        System.out.println("forEach Demo");
        Stream.of("AAA","BBB","CCC").forEach(s->System.out.println("Output:"+s));
        System.out.println("forEachOrdered Demo");
        Stream.of("AAA","BBB","CCC").forEachOrdered(s->System.out.println("Output:"+s));
    }
} 
Find the output.
forEach Demo
Output:AAA
Output:BBB
Output:CCC
forEachOrdered Demo
Output:AAA
Output:BBB
Output:CCC 

Stream.peek

peek() is an intermediate operation. It returns a new stream which consists all the elements of stream after applying the Consumer.
PeekDemo.java
package com.concretepage.util.stream;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class PeekDemo {
    public static void main(String[] args) {
        List<Integer> list = Arrays.asList(10,11,12);
        list.stream().peek(i->System.out.println(i*i)).collect(Collectors.toList());
    }    
} 
Find the output.
100
121
144 

Stream.skip

skip() is a method that skips given number of element from the stream object from start.
SkipDemo.java
package com.concretepage.util.stream;
import java.util.Arrays;
import java.util.List;
public class SkipDemo {
    public static void main(String[] args) {
        List<String> list = Arrays.asList("AA","BB","CC","DD");
        list.stream().skip(2).forEach(s->System.out.println(s));
    }    
} 
Find the output.
CC
DD 

Stream.toArray

toArray() method converts a stream into an array.
ToArrayDemo.java
package com.concretepage.util.stream;
import java.util.stream.Stream;
public class ToArrayDemo {
    public static void main(String[] args) {
        Object[] ob = Stream.of("A","B","C","D").toArray();
        for (Object o : ob) {
            System.out.println(o.toString());
        }
    }
} 
Find the output.
A
B
C
D 
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS


©2018 concretepage.com | Privacy Policy | Contact Us