Tuesday, August 12, 2014

Example of using java.util.function.Consumer

Java 8 introduce java.util.function.Consumer, a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.

This example show ways to print all elements in a List. Also show how to implement our Consumer.

package java8consumer;

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

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class Java8Consumer {

    public static void main(String[] args) {
        List myList = new ArrayList();
        for(int i=0; i<=5; i++){
            myList.add(i);
        }
        
        for(int i=0; i<myList.size(); i++){
            System.out.println(myList.get(i));
        }
        
        for (Object ele : myList) {
            System.out.println(ele);
        }
        
        myList.forEach((ele) -> System.out.println(ele)); 
        
        //Use Consumer
        MyConsumer myConsumer = new MyConsumer();
        myList.forEach(myConsumer);
    }
    
}

class MyConsumer implements Consumer{

    @Override
    public void accept(Object t) {
        System.out.println(t);
    }

}


java.util.function.Consumer example

No comments:

Post a Comment