Java 8 IntConsumer, LongConsumer and DoubleConsumer forEach Example

In this source code example, we create the three types of consumers and iterate over them with forEach()

Since Java 8, we have built-in consumer interfaces for primitive data types: IntConsumer, LongConsumer and DoubleConsumer.

Java 8 Consumer forEach Example


import java.util.Arrays;
import java.util.function.DoubleConsumer;
import java.util.function.IntConsumer;
import java.util.function.LongConsumer;

public class JavaForEachConsSpec {

    public static void main(String[] args) {

        int[] inums = { 3, 5, 6, 7, 5 };
        IntConsumer icons = i -> System.out.print(i + " ");
        Arrays.stream(inums).forEach(icons);
        
        System.out.println();

        long[] lnums = { 13L, 3L, 6L, 1L, 8L };
        LongConsumer lcons = l -> System.out.print(l + " ");
        Arrays.stream(lnums).forEach(lcons);
        
        System.out.println();

        double[] dnums = { 3.4d, 9d, 6.8d, 10.3d, 2.3d };
        DoubleConsumer dcons = d -> System.out.print(d + " ");
        Arrays.stream(dnums).forEach(dcons);
        
        System.out.println();
    }
}

Output:

3 5 6 7 5 
13 3 6 1 8 
3.4 9.0 6.8 10.3 2.3 

Free Spring Boot Tutorial - 5 Hours Full Course


Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course

Comments