Consumer is a functional interface that takes one Type T argument and has no return value.
@FunctionalInterface
public interface Consumer<T> {
/**
* Performs this operation on the given argument.
*
* @param t the input argument
*/
void accept(T t);
}Example 1 : Consumer
Consumers can be implemented as Lambda expressions. Passing arguments with the accept() call will do the implementation.
import java.util.function.Consumer;
public class ConsumerExample1 {
public static void main(String[] args) {
Consumer<String> consumer = s -> System.out.println(s.toUpperCase());
consumer.accept("hello world");
}
}Output:
HELLO WORLDExample 2 : Primitive Consumer
Java provides a Consumer class for primitive types. In addition to IntConsumer, there are DoubleConsumer and LongConsumer.
import java.util.function.IntConsumer;
public class ConsumerExample2 {
public static void main(String[] args) {
IntConsumer consumer = n -> System.out.println(n * 100);
consumer.accept(5);
consumer.accept(10);
}
}Output:
500
1000Example 3 : List.forEach()
List.forEach() takes a Consumer as an argument.
You can print all items in the List using Consumer as follows.
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
public class ConsumerExample3 {
public static void main(String[] args) {
Consumer<String> consumer = s -> System.out.println(s.toUpperCase());
List<String> list = Arrays.asList("apple", "kiwi", "orange");
list.forEach(consumer);
}
}Output:
APPLE
KIWI
ORANGEExample 4 : andThen()
andThen() is a chaining method that connects consumers.
When calling addNumber.andThen(printList).accept(fruits) in the code below, printList() is executed after printList().
The argument passed to both methods is fruits, and the same object is passed.
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
public class ConsumerExample4 {
public static void main(String[] args) {
List<String> fruits = Arrays.asList("apple", "kiwi", "orange");
Consumer<List<String>> addNumber = list -> {
for (int i = 0; i < list.size(); i++) {
list.set(i, (i + 1) + ". " + list.get(i));
}
};
Consumer<List<String>> printList = list -> {
for (String fruit : list) {
System.out.println(fruit);
}
};
addNumber.andThen(printList).accept(fruits);
}
}Output:
1. apple
2. kiwi
3. orangeActually andThen() is implemented as below.
// Consumer.java
public interface Consumer<T> {
...
default Consumer<T> andThen(Consumer<? super T> after) {
Objects.requireNonNull(after);
return (T t) -> { accept(t); after.accept(t); };
}
}Example 5 : Passing Consumer as a function argument (Higher Order Function)
You can define a function that takes a Consumer as an argument as follows.
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
public class ConsumerExample5 {
public static void main(String[] args) {
List<String> fruits = Arrays.asList("apple", "kiwi", "orange");
Consumer<String> printFruit = fruit -> System.out.println("I like " + fruit);
forEach(fruits, printFruit);
}
static <T> void forEach(List<T> list, Consumer<T> consumer) {
for (T t : list) {
consumer.accept(t);
}
}
}Output:
I like apple
I like kiwi
I like orangeReferences
Related Posts
- Java - Remove items from List while iterating
- Java - How to find key by value in HashMap
- Java - Update the value of a key in HashMap
- Java - How to put quotes in a string
- Java - How to put a comma (,) after every 3 digits
- BiConsumer example in Java 8
- Java 8 - Consumer example
- Java 8 - BinaryOperator example
- Java 8 - BiPredicate Example
- Java 8 - Predicate example
- Java 8 - Convert Stream to List
- Java 8 - BiFunction example
- Java 8 - Function example
- Java - Convert List to Map
- Exception testing in JUnit
- Hamcrest Collections Matcher
- Hamcrest equalTo () Matcher
- AAA pattern of unit test (Arrange/Act/Assert)
- Hamcrest Custom Matcher
- Hamcrest Text Matcher
- Why Junit uses Hamcrest
- Java - ForkJoinPool
- Java - How to use Futures
- Java - Simple HashTable implementation
- Java - Create a file in a specific path
- Java - Mockito의 @Mock, @Spy, @Captor, @InjectMocks
- Java - How to write test code using Mockito
- Java - Synchronized block
- Java - How to decompile a ".class" file into a Java file (jd-cli decompiler)
- Java - How to generate a random number
- Java - Calculate powers, Math.pow()
- Java - Calculate the square root, Math.sqrt()
- Java - How to compare String (==, equals, compare)
- Java - Calculate String Length
- Java - case conversion & comparison insensitive (toUpperCase, toLowerCase, equalsIgnoreCase)