Thursday, April 9, 2015

Java 8 For Each with Consumer example

Goal
Java 8 comes with new features which adds forEach and Consumer to its list. Lets write a simple piece of code that uses forEach and Consumer<> to print the elements on screen.

Setup
Following code is given to us and need to fill in the blank to print the elements.

@Test
    public void SimpleCollection() {
        List values = Arrays.asList(1, 2, 3, 4, 5, 6);

        values.forEach(/** fill with Consumer and print to screen.**/
);

    }

Solution
We can use follwing code to fill in the blank. This code uses Consumer and implements the method accept(). In accept() we can write any piece of logic. Here we will simply print elements on screen.

new Consumer() {
            public void accept(Integer value) {
                System.out.println(value);
            }

The complete program looks like as following :

@Test
    public void SimpleCollection() {
        List values = Arrays.asList(1, 2, 3, 4, 5, 6);

        values.forEach(new Consumer() {
            public void accept(Integer value) {
                System.out.println(value);
            }
        });

    }

No comments:

Post a Comment