Java Consumer
last modified July 6, 2020
Java Consumer tutorial shows how to work with the Consumer functional interface in Java.
Consumer
Java Consumer is a functional interface which represents an operation
that accepts a single input argument and returns no result. Unlike most other
functional interfaces, Consumer
is expected to operate via side-effects.
@FunctionalInterface public interface Consumer<T> { void accept(T t); }
The Consumer's
functional method is accept(Object)
. It
can be used as the assignment target for a lambda expression or method
reference.
Java Consumer example
The following example creates a simple consumer.
package com.zetcode; import java.util.function.Consumer; public class ConsumerEx { public static void main(String[] args) { Consumer<String> showThreeTimes = value -> { System.out.println(value); System.out.println(value); System.out.println(value); }; showThreeTimes.accept("blue sky"); showThreeTimes.accept("old falcon"); } }
The showThreeTimes
consumer prints the input three times.
blue sky blue sky blue sky old falcon old falcon old falcon
This is the output.
Java IntConsumer
IntConsumer
represents an operation that accepts a single
int-valued argument and returns no result. This is the primitive type
specialization of Consumer for int
.
package com.zetcode; import java.util.function.Consumer; import java.util.function.IntConsumer; public class ConsumerEx2 { public static void main(String[] args) { Consumer<Integer> printMultiplyBy100 = (val) -> System.out.println(val * 100); printMultiplyBy100.accept(3); printMultiplyBy100.accept(4); printMultiplyBy100.accept(5); IntConsumer printMultiplyBy500 = a -> System.out.println(a * 50); printMultiplyBy500.accept(1); printMultiplyBy500.accept(2); printMultiplyBy500.accept(3); } }
In the example, the consumers multiply the input value.
300 400 500 50 100 150
This is the output.
Java Consumer forEach
The forEach
method accepts a Consumer
as a parameter.
The consumer can be simplified with a lambda expression or a method reference.
package com.zetcode; import java.util.List; import java.util.function.Consumer; public class ConsumerEx3 { public static void main(String[] args) { var words = List.of("falcon", "wood", "rock", "forest", "river", "water"); words.forEach(new Consumer<String>() { @Override public void accept(String s) { System.out.println(s); } }); } }
In the example, we go over the elements of a list with forEach
.
The consumer simply prints each of the elements.
falcon wood rock forest river water
This is the output.
Java Consumer andThen
The andThen
method returns a composed Consumer
that
performs, in sequence, this operation followed by the next operation.
package com.zetcode; import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; public class ConsumerEx4 { public static void main(String[] args) { var vals = new ArrayList<Integer>(); vals.add(2); vals.add(4); vals.add(6); vals.add(8); Consumer<List<Integer>> addTwo = list -> { for (int i = 0; i < list.size(); i++) { list.set(i, 2 + list.get(i)); } }; Consumer<List<Integer>> showList = list -> list.forEach(System.out::println); addTwo.andThen(showList).accept(vals); } }
In the example, we add value 2 to each of the elements in the list and then we print all the elements.
4 6 8 10
This is the output.
In the following example, we work with a list of products.
package com.zetcode; import java.math.BigDecimal; public class Product { private String name; private BigDecimal price; public Product(String name, BigDecimal price) { this.name = name; this.price = price; } public String getName() { return name; } public void setName(String name) { this.name = name; } public BigDecimal getPrice() { return price; } public void setPrice(BigDecimal price) { this.price = price; } @Override public String toString() { var sb = new StringBuilder("Product{"); sb.append("name='").append(name).append('\''); sb.append(", price=").append(price); sb.append('}'); return sb.toString(); } }
This is the Product
class.
package com.zetcode; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; public class ConsumerEx5 { private static RoundingMode ROUNDING_MODE = RoundingMode.HALF_EVEN; private static int DECIMALS = 2; public static void main(String[] args) { List<Product> products = new ArrayList<>(); products.add(new Product("A", new BigDecimal("2.54"))); products.add(new Product("B", new BigDecimal("3.89"))); products.add(new Product("C", new BigDecimal("5.99"))); products.add(new Product("D", new BigDecimal("9.99"))); Consumer<Product> incPrice = p -> { p.setPrice(rounded(p.getPrice().multiply(new BigDecimal("1.1")))); }; process(products, incPrice.andThen(System.out::println)); } private static BigDecimal rounded(BigDecimal number){ return number.setScale(DECIMALS, ROUNDING_MODE); } private static void process(List<Product> data, Consumer<Product> cons) { for (var e : data) { cons.accept(e); } } }
This example increases the prices of products by 10%.
Consumer<Product> incPrice = p -> { p.setPrice(rounded(p.getPrice().multiply(new BigDecimal("1.1")))); };
The consumer increases the product price by 10% and rounds the value.
process(products, incPrice.andThen(System.out::println));
We increase the prices and then print the modified products.
private static void process(List<Product> data, Consumer<Product> cons) { for (var e : data) { cons.accept(e); } }
The consumer is applied on each product of the list.
Product{name='A', price=2.79} Product{name='B', price=4.28} Product{name='C', price=6.59} Product{name='D', price=10.99}
This is the output.
Java Consumer custom forEach
The following example creates a custom, generic forEach method.
package com.zetcode; import java.util.List; import java.util.function.Consumer; public class ConsumerEx5 { public static void main(String[] args) { var data = List.of(1, 2, 3, 4, 5, 6, 7); // Consumer<Integer> consumer = (Integer x) -> System.out.println(x); Consumer<Integer> consumer = System.out::println; forEach(data, consumer); System.out.println("--------------------------"); forEach(data, System.out::println); } static <T> void forEach(List<T> data, Consumer<T> consumer) { for (T t : data) { consumer.accept(t); } } }
We have a list of integers. We print all the elements of the list with a custom forEach method.
1 2 3 4 5 6 7 -------------------------- 1 2 3 4 5 6 7
This is the output.
In this tutorial, we have worked with Java Consumer interface.
List all Java tutorials.