Java Consumer Tutorial with Examples
1. Consumer
No ADS
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
No ADS
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
No ADS
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
No ADS
Java Basic
- Data Types in java
- Java PhantomReference Tutorial with Examples
- JDK Javadoc in CHM format
- Java Stream Tutorial with Examples
- Java Predicate Tutorial with Examples
- Java BiConsumer Tutorial with Examples
- Arrays in Java
- JDBC Driver Libraries for different types of database in Java
- Abstract class and Interface in Java
- Java Commons Email Tutorial with Examples
- Install Eclipse
- Bitwise Operations
- Install Eclipse on Ubuntu
- Configuring Eclipse to use the JDK instead of JRE
- Java Commons Logging Tutorial with Examples
- Java Enums Tutorial with Examples
- Loops in Java
- Java Regular Expressions Tutorial with Examples
- Install Java on Ubuntu
- Quick Learning Java for beginners
- Install Java on Windows
- Comparing and Sorting in Java
- Inheritance and polymorphism in Java
- Java Consumer Tutorial with Examples
- Java String, StringBuffer and StringBuilder Tutorial with Examples
- Java Exception Handling Tutorial with Examples
- Example of Java encoding and decoding using Apache Base64
- if else statement in java
- Switch Statement in Java
- Java Supplier Tutorial with Examples
- Java Programming for team using Eclipse and SVN
- Java JDBC Tutorial with Examples
- Java remote method invocation - Java RMI Tutorial with Examples
- Java Multithreading Programming Tutorial with Examples
- Customize java compiler processing your Annotation (Annotation Processing Tool)
- What is needed to get started with Java?
- Java Aspect Oriented Programming with AspectJ (AOP)
- Understanding Java System.identityHashCode, Object.hashCode and Object.equals
- Java Compression and Decompression Tutorial with Examples
- Java Reflection Tutorial with Examples
- Install OpenJDK on Ubuntu
- Java String.format() and printf() methods
- History of Java and the difference between Oracle JDK and OpenJDK
- Introduction to the Raspberry Pi
- Java Socket Programming Tutorial with Examples
- Java Generics Tutorial with Examples
- Manipulating files and directories in Java
- Java WeakReference Tutorial with Examples
- Java Commons IO Tutorial with Examples
- History of bits and bytes in computer science
- Which Platform Should You Choose for Developing Java Desktop Applications?
- Java SoftReference Tutorial with Examples
- Syntax and new features in Java 8
- Java Annotations Tutorial with Examples
- Java Function Tutorial with Examples
- Access modifiers in Java
- Java BiFunction Tutorial with Examples
- Get the values of the columns automatically increment when Insert a record using JDBC
- Java Functional Interface Tutorial with Examples
- Java BiPredicate Tutorial with Examples
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