Java Consumer Tutorial with Examples
1. Consumer
In Java 8, Consumer is a functional interface, representing an operator that accepts an input parameter and returns nothing.
Consumer
@FunctionalInterface
public interface Consumer<T> {
void accept(T t);
default Consumer<T> andThen(Consumer<? super T> after) {
Objects.requireNonNull(after);
return (T t) -> {
accept(t);
after.accept(t);
};
}
}
Example:
ConsumerEx1.java
package org.o7planning.ex;
import java.util.function.Consumer;
public class ConsumerEx1 {
public static void main(String[] args) {
// Create a Consumer object directly
Consumer<String> greeter = name -> System.out.println("Hello " + name);
greeter.accept("Tran"); // Hello Tran
}
}
Expanding the above example, we use Consumer in Stream.forEach method.
// A method of Stream class
public void forEach(Consumer<? super T> action);
ConsumerEx2.java
package org.o7planning.ex;
import java.util.function.Consumer;
import java.util.stream.Stream;
public class ConsumerEx2 {
public static void main(String[] args) {
// Create a Consumer object directly
Consumer<String> greeter = name -> System.out.println("Hello " + name);
Stream<String> names = Stream.of("Tran", "Nguyen", "Pham");
names.forEach(greeter);
}
}
Output:
Hello Tran
Hello Nguyen
Hello Pham
Below is a list of the methods in the java.util package using Consumer:
Modifier and Type | Method and Description |
void | ArrayList.forEach(Consumer<? super E> action) |
void | Vector.forEach(Consumer<? super E> action) |
default void | PrimitiveIterator.OfDouble.forEachRemaining(Consumer<? super Double> action) |
default void | Spliterator.OfDouble.forEachRemaining(Consumer<? super Double> action) |
default void | Iterator.forEachRemaining(Consumer<? super E> action) |
default void | PrimitiveIterator.OfInt.forEachRemaining(Consumer<? super Integer> action) |
default void | Spliterator.OfInt.forEachRemaining(Consumer<? super Integer> action) |
default void | PrimitiveIterator.OfLong.forEachRemaining(Consumer<? super Long> action) |
default void | Spliterator.OfLong.forEachRemaining(Consumer<? super Long> action) |
default void | Spliterator.forEachRemaining(Consumer<? super T> action) |
void | Optional.ifPresent(Consumer<? super T> consumer) |
default boolean | Spliterator.OfDouble.tryAdvance(Consumer<? super Double> action) |
default boolean | Spliterator.OfInt.tryAdvance(Consumer<? super Integer> action) |
default boolean | Spliterator.OfLong.tryAdvance(Consumer<? super Long> action) |
boolean | Spliterator.tryAdvance(Consumer<? super T> action) |
See also: BiConsumer is a class similar to Consumer, the difference is that it accepts 2 parameters:
2. Consumer + Method reference
If a method has a single parameter and returns nothing, its reference can be considered a Consumer.
Example: System.out.println(param) method takes one parameter and returns nothing, then its reference System.out::println will be considered as a Consumer.
ConsumerEx5.java
package org.o7planning.ex;
import java.util.function.Consumer;
public class ConsumerEx5 {
public static void main(String[] args) {
myPrintln(System.out::println, "Hello World!");
}
public static <T> void myPrintln(Consumer<T> c, T t) {
c.accept(t);
}
}
Output:
Hello World!
Example:
ConsumerEx6.java
package org.o7planning.ex;
import java.util.stream.Stream;
public class ConsumerEx6 {
public static void main(String[] args) {
Stream<String> names = Stream.of("Tran", "Nguyen", "Pham");
// Call method: Stream.forEach(Consumer)
names.forEach(System.out::println);
}
}
Output:
Tran
Nguyen
Pham
- Java Method Reference
- Java Stream
3. Consumer.andThen
andThen(after) method returns an associated Consumer. First, the current Consumer will be called then after will be called. If an error occurs in one of the two steps above, the error will be passed to the caller. If an error occurs at the current Consumer then after is ignored.
Consumer
default Consumer<T> andThen(Consumer<? super T> after) {
Objects.requireNonNull(after);
return (T t) -> {
accept(t);
after.accept(t);
};
}
Example:
ConsumerEx3.java
package org.o7planning.ex;
import java.util.function.Consumer;
public class ConsumerEx3 {
public static void main(String[] args) {
Consumer<String> c = text -> System.out.println(text.toLowerCase());
c.andThen(c).accept("Hello");
}
}
The result is that the word "hello" was printed out twice.
hello
hello
Example:
ConsumerEx4.java
package org.o7planning.ex;
import java.util.function.Consumer;
public class ConsumerEx4 {
public static void main(String[] args) {
Consumer<UserAccount> c1 = test -> test.auth();
Consumer<UserAccount> c2 = test -> test.welcome();
UserAccount user = new UserAccount("tran", "123");
try {
c1.andThen(c2).accept(user);
} catch (Exception e) {
}
}
public static class UserAccount {
private String userName;
private String password;
public UserAccount(String userName, String password) {
this.userName = userName;
this.password = password;
}
public void auth() {
if ("123".equals(password)) {
System.out.println("Valid Account!");
} else {
throw new RuntimeException("Invalid Password");
}
}
public void welcome() {
System.out.println("Welcome! " + this.userName);
}
}
}
Output:
Valid Account!
Welcome! tran
Java Basic
- Customize java compiler processing your Annotation (Annotation Processing Tool)
- Java Programming for team using Eclipse and SVN
- Java WeakReference Tutorial with Examples
- Java PhantomReference Tutorial with Examples
- Java Compression and Decompression Tutorial with Examples
- Configuring Eclipse to use the JDK instead of JRE
- Java String.format() and printf() methods
- Syntax and new features in Java 8
- Java Regular Expressions Tutorial with Examples
- Java Multithreading Programming Tutorial with Examples
- JDBC Driver Libraries for different types of database in Java
- Java JDBC Tutorial with Examples
- Get the values of the columns automatically increment when Insert a record using JDBC
- Java Stream Tutorial with Examples
- Java Functional Interface Tutorial with Examples
- Introduction to the Raspberry Pi
- Java Predicate Tutorial with Examples
- Abstract class and Interface in Java
- Access modifiers in Java
- Java Enums Tutorial with Examples
- Java Annotations Tutorial with Examples
- Comparing and Sorting in Java
- Java String, StringBuffer and StringBuilder Tutorial with Examples
- Java Exception Handling Tutorial with Examples
- Java Generics Tutorial with Examples
- Manipulating files and directories in Java
- Java BiPredicate Tutorial with Examples
- Java Consumer Tutorial with Examples
- Java BiConsumer Tutorial with Examples
- What is needed to get started with Java?
- History of Java and the difference between Oracle JDK and OpenJDK
- Install Java on Windows
- Install Java on Ubuntu
- Install OpenJDK on Ubuntu
- Install Eclipse
- Install Eclipse on Ubuntu
- Quick Learning Java for beginners
- History of bits and bytes in computer science
- Data Types in java
- Bitwise Operations
- if else statement in java
- Switch Statement in Java
- Loops in Java
- Arrays in Java
- JDK Javadoc in CHM format
- Inheritance and polymorphism in Java
- Java Function Tutorial with Examples
- Java BiFunction Tutorial with Examples
- Example of Java encoding and decoding using Apache Base64
- Java Reflection Tutorial with Examples
- Java remote method invocation - Java RMI Tutorial with Examples
- Java Socket Programming Tutorial with Examples
- Which Platform Should You Choose for Developing Java Desktop Applications?
- Java Commons IO Tutorial with Examples
- Java Commons Email Tutorial with Examples
- Java Commons Logging Tutorial with Examples
- Understanding Java System.identityHashCode, Object.hashCode and Object.equals
- Java SoftReference Tutorial with Examples
- Java Supplier Tutorial with Examples
- Java Aspect Oriented Programming with AspectJ (AOP)
Show More
- Java Servlet/Jsp Tutorials
- Java Collections Framework Tutorials
- Java API for HTML & XML
- Java IO Tutorials
- Java Date Time Tutorials
- Spring Boot Tutorials
- Maven Tutorials
- Gradle Tutorials
- Java Web Services Tutorials
- Java SWT Tutorials
- JavaFX Tutorials
- Java Oracle ADF Tutorials
- Struts2 Framework Tutorials
- Spring Cloud Tutorials