Java 8 Lambda – Simple explanation of the Consumer Interface

I have not found a simple explanation of how the consumer interface works and how to use it in a lambda expression. Hopefully I will help you guys to see how easy it is to use and you will also simplify your code.
The legacy way to create a List and loop through it :

public class ConventionalForLoop {
    
    public static void main(String[] args) {
        List<Integer> il = new ArrayList<>();
        il.add(10); il.add(15); il.add(20); il.add(25);

        for (Iterator<Integer> i = il.iterator(); i.hasNext();) {
            Integer item = i.next();
            System.out.println("For Loop Value :" + item);
        }
    }
}
Now with Java 8 we can use a Consumer Interface and for explanation I have declared it.

public class ShowConsumer {
    public static void main(String[] args) {
        class ConsumeInt implements Consumer<Integer>
            {
                @Override
                public void accept(Integer i) {
                    System.out.println("Value From Consumer :" + i.toString());
                }
            }
        List<Integer> arrl = Arrays.asList(10,15,20,25);
        ConsumeInt ci = new ConsumeInt();
        arrl.forEach(ci);
    }
With the lambda expression it is very simple :

public class ShowConsumer {
    public static void main(String[] args) {
        List<Integer> arrl = Arrays.asList(10,15,20,25);
        arrl.forEach(i -> System.out.println("Value From Consumer :" + i.toString()));
    }
}

Leave a Reply

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


CAPTCHA Image
Reload Image