Java function reference with consumer with accept

Java 8 introduces functional interface Consumer. Consumer is used when an object needs to be consumed as input and execution happens using functional method is accept(Object). It does not return any result.

The assignment target can be lambda expression or method reference. Following is an example of method reference of Consumer interface with accept.

public static void main(String args[]) {
        Consumer<String> consume = Practice::toUpperCase;
        //Consumer <String> consume = this::toLowerCase;

        String[] strArr = {"Foo", "Bar"};
        printString(strArr, consume);
    }
    public static void printString(String[] strArr, Consumer < String > consumer) {
        for (String str:strArr) {
            consumer.accept(str);
        }
    }

    private static void toUpperCase(String str){
        System.out.println(str.toUpperCase());
    }

    private static void toLowerCase(String str){
        System.out.println(str.toLowerCase());
    }
Share

Leave a Reply

Your email address will not be published. Required fields are marked *