Month: September 2016

Java 8 – Consumer Example

Posted on Updated on

Java 8 – Consumer Example 

Consumjava-8-lambdaer<T> introduced in Java 8.  Although it is a Functional Interface that  accepts only one argument and  operation to be performed on that argument but do not return anything.

Since It has only one method i.e

accept( T t);  //Performs this operation on the given argument.

and another method which is a default method– As you know that since Java 8, An Interface can be  a default method implementation which is denoted as default keyword.

default Consumer<T> andThen(Consumer<? super T> after)

Basically, this default method performs a sequence of composed consumers operation that followed by the after operation.

Below is some example that’s build up you understanding of Consumer<T> concept :-

 


package com.example1;

import java.util.Collection;
import java.util.List;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Created by MYPC on 9/19/2016.
 */
public class ConsumerTest {

    public static void main(String[] args) {

        /**
         * Example 1
         */
        List integerList = Stream.of(new Integer(1), new Integer(10), new Integer(200), new Integer(101), new Integer(-10), new Integer(0))
                .collect(Collectors.toList());
        forEach(integerList, (number) -> {
            System.out.println(" Number is " + number);
        });

        /**
         * Example 2
         */
        Consumer consumer = (number) -> {
            number += number;
            System.out.println(number);
        };

        /**
         * Example 3
         */
        consumer.accept(2000);
        getConsumer().accept(1000);

        /**
         * Example 4
         */
        integerList.forEach((num -> {
            System.out.println("Java 8 forEach Loop" + num);
        }));


    }

    /**
     * Return consumer that to be applied on accept(T t) parameter.
     *
     * @return
     */
    public static Consumer getConsumer() {
        return (number) -> System.out.println("Method Invoked here " + number);
    }

    /**
     * Iterate over the Collection and to be consumed by console or other system.
     *
     * @param collections
     * @param consumer
     * @param 
     */
    public static  void forEach(Collection collections, Consumer consumer) {
        collections.forEach(consumer);
    }
}


Let’s move to some other example:-

In the example, we have tried to create a generic forEach loop that’s iterating over the generated Query result and consume by some other object.

ExecutorContext.Java – Object consume data producted by getQuery().


import java.util.List;
import java.util.function.Consumer;

interface ExecutorContext {
    List getQuery();
    Consumer getConsumer();
}


StubsUtils.Java : – Utility class


class StubsUtils {

    public static void forEach(ExecutorContext executorContext) {
        executorContext.getQuery().forEach(executorContext.getConsumer());
    }
}
 

Java8ConsumerExample.Java :- This is  a Consumer client that invoked forEach loop and override  ExecutorConext interface to produce & consume the query set elements.

Here, getQuery() method returns a Collection  but it could be any Result set query that will be produced a result set by JdbcTemplate. Other method  getConsumer() will be applied the desired operation over the each element of Collection returned by getQuery() method means printing on consoles and adding into a list.

Inside the getConsumer(), you can probably apply your logic to perform the operation over the Input argument.


import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Java8ConsumerExample {

    private static List QUERY_RESULTSET_INTEGER = Arrays.asList(new Integer(1), new Integer(10), new Integer(200), new Integer(101), new Integer(-10), new Integer(0));
    private static List QUERY_RESULTSET_STRING = Stream.of("A", "B", "C", "D", "E", "F").collect(Collectors.toList());

    public static void main(String[] args) {

        // EXAMPLE : 1

        /**
         * Iterator over the Query generated integer list and print on console.
         */
        StubsUtils.forEach(new ExecutorContext() {
            List consumerList = new ArrayList();

            /**
             * Let's assume that our query returns set of Integer that would be consume by some caller class or print on console.
             * @return
             */
            @Override
            public List getQuery() {
                return QUERY_RESULTSET_INTEGER;
            }

            @Override
            public Consumer getConsumer() {
                return x -> {
                    System.out.println(x);
                    consumerList.add(x);
                };
            }
        });

        // EXAMPLE : 2
        /**
         * Iterator over the Query generated String list and print on console.
         */
        StubsUtils.forEach(new ExecutorContext() {
            List consumerList = new ArrayList();

            /**
             * Let's assume that our query returns set of Integer that would be consume by some caller class or print on console.
             * @return
             */
            @Override
            public List getQuery() {
                return QUERY_RESULTSET_STRING;
            }

            @Override
            public Consumer getConsumer() {
                return x -> {
                    System.out.println(x);
                    consumerList.add(x);
                };
            }
        });

    }
}


Output:-

1 10 200 101 -10 0
A B C D E F