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:

  1. 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);
  1. agree
consumer.accept("Hello World");

This will display “Hello World”.

  1. and after that
  2. and following that
  3. 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.

bannerAds