Java 8: Consumer – Built-In Functional Interfaces

Consumer Interface is another Built-In Functional Interface of java.util.function package of Java 8. The consumer interface consumes the object and doesn’t return any object. it has only one abstract method called accept(). Along with this, it has one more default method called andThen()

				
					void accept(T t) // abstract method

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

Example for Consumer Interface

				
					public class ConsumerExample
{
    public static void main(String[] args) {
        Consumer<String> msg = a -> System.out.println(a);
        
        msg.accept("Hello World");
    }
}
				
			

Output

				
					Hello World
				
			

andThen() method of Consumer Interface

andThen() method is a default method of Consumer Function Interface. andThen() method accepts a consumer interface as a parameter called after which to be applied after the current one.

Below is the example to square each number and print of a list:

				
					public class ConsumerExample
{
    public static void main(String[] args) {
        
        //Multiply by 2 each Integer element
        Consumer<List<Integer>> doubleValue = a -> {
          for(int i=0; i<a.size();i++)
                a.set(i,2*a.get(i));
        };
        
        //Print Each element of List
        Consumer<List<Integer>> printValue = a ->{
            a.stream().forEach(p->System.out.println(p));
        };
        
       List<Integer> values = new ArrayList<>(Arrays.asList(3,4,5));
       doubleValue.andThen(printValue).accept(values);
    }
}
				
			

Output

				
					6
8
10
				
			

Conclusion

In this article, we have seen consumer interfaces with some examples.

Java 8 Stream APIs

Java 8: Introduction to Streams API

Java 8 got a brand new API called streams. it makes every developer’s life easy. Stream APIs are used to process the group of data. mostly streams are applied on collection objects but we can use stream with any group

Read More »