What is the usage of Java consumer?
In Java, a Consumer is a functional interface used to represent an operation that takes a parameter and does not return a result. It defines an abstract method called accept, which takes a parameter and performs the necessary operation.
The usage of Consumer can be achieved through the following steps:
- Create a Consumer object: You can use a Lambda expression or method reference to create a Consumer object. For example:
Consumer<String> consumer = (str) -> System.out.println(str);
- agree
consumer.accept("Hello World");
This will display “Hello World”.
- and after that
- and following that
- and next
Consumer<String> consumer1 = (str) -> System.out.println(str);
Consumer<String> consumer2 = (str) -> System.out.println(str.toUpperCase());
Consumer<String> chainedConsumer = consumer1.andThen(consumer2);
chainedConsumer.accept("Hello World");
This will first print “Hello World” and then print “HELLO WORLD”.
One of the uses of Consumer is to process elements in collection operations, such as performing a specific operation on each element in the collection. It can be used in conjunction with the Stream API in Java 8, for example:
List<String> list = Arrays.asList("Apple", "Banana", "Orange");
list.stream().forEach((str) -> System.out.println(str));
This will output “Apple”, “Banana”, and “Orange” respectively.