Java 8 Consumer Example

Author: Brian Nettles | Date Created: May 21, 2018 | Visits: 105

The Consumer class which is new to Java 8 give a new way to iterate through arrays. It also provides a hook for the companion predicate class which helps filter out items in the array. In this post, we are focusing strictly on the Consumer class with a basic example for you to analyze as a sample.

From the example you can see that the usage of the Consumer class enables the creator to access new ways of performing actions on the Array in a systematic and easy to follow way once again making code less verbose and easy to follow.


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

public class ConsumerExample {
	
	public ConsumerExample() {
		FruitTree tree1 = this.new FruitTree("Orange");
		FruitTree tree2 = this.new FruitTree("Apricot");
		FruitTree tree3 = this.new FruitTree("Peach");
		FruitTree tree4 = this.new FruitTree("Pear");
		List<FruitTree> fruitTrees = Arrays.asList(tree1, tree2, tree3, tree4);
		
		// Option 1 - something simple
		for(int i=0; i<fruitTrees.size();i++) {
			FruitTree tree = fruitTrees.get(i);
			// do something
			System.out.println("1 " + "We are doing something.");
			
			// do something else
			System.out.println("1 " + tree.getName());			
		}

		// Option 2 - same a something simple using Consumer
		// by nature of the Lambda expression, ft is the FruitTree object derived from the array when applied.
		Consumer<FruitTree> consumer1 = ft -> {
		  System.out.println("2 " + "We are doing something");
		};
		
		Consumer<FruitTree> consumer2 = ft -> {
			System.out.println("2 " + ft.getName());
		};
		
		fruitTrees.forEach(consumer1.andThen(consumer2));
		
	}
	
	public static void main(String args[]) {
		ConsumerExample ce = new ConsumerExample();
	}
	
	
	class FruitTree{
		
		String name;
		
		FruitTree(String name) {
			this.name=name;
		}
		
		String getName() {
			return this.name;
		}
	}
}

 
Trisummit Technologies
6421 N. Lena Place
Tucson, AZ 85741
575-322-6697
© 2018 All Rights Reserved