Consumer
是Java中java.util.function
包下的一个函数式接口。它定义了一个接受单个输入参数并且没有返回值的操作。Consumer
接口包含一个名为accept
的抽象方法,该方法接受一个参数并在其上执行操作。
@FunctionalInterface
public interface Consumer<T> {
void accept(T t); // 可能包含其他默认方法和静态方法
}
Consumer
通常用于表示在某个数据结构(例如集合)上的元素级操作。它允许你执行对集合中的每个元素进行的一些操作,而不需要显式使用循环。以下是一些使用Consumer
的场景和示例:
场景1: 遍历集合并执行操作
import java.util.Arrays;
import java.util.List;
public class ConsumerExample {
public static void main(String[] args) {
List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David"); // 使用 Consumer 遍历集合并打印每个元素
names.forEach(name -> System.out.println("Hello, " + name));
}
}
在这个例子中,forEach
方法接受一个Consumer
作为参数,该Consumer
定义了对集合中每个元素的操作,这里是打印每个元素的“Hello”。
场景2: 修改集合中的元素
import java.util.ArrayList;
import java.util.List;
public class ConsumerExample {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5)); // 使用 Consumer 修改集合中的元素,将每个元素乘以2
numbers.forEach(number -> { int doubled = number * 2; System.out.println("Original: " + number + ", Doubled: " + doubled); });
}
}
在这个例子中,forEach
方法接受一个Consumer
,该Consumer
将每个元素乘以2,并打印出原始值和新值。
场景3: 资源管理
import java.io.Closeable;
public class ResourceManagementExample {
public static void main(String[] args) { // 使用 Consumer 进行资源管理,确保资源在使用后被正确关闭
withResource(resource -> {
// 操作资源 System.out.println("Using resource: " + resource);
});
}
// 使用 Consumer 进行资源管理 private static void withResource(Consumer<Closeable> resourceConsumer) {
try (Closeable resource = acquireResource()) { // 在资源上执行操作 resourceConsumer.accept(resource);
} catch (Exception e) {
e.printStackTrace(); } } // 模拟获取资源 private static Closeable acquireResource() {
return () -> System.out.println("Closing resource");
}
}
在这个例子中,withResource
方法接受一个Consumer<Closeable>
,确保在资源使用完成后资源会被正确关闭。acquireResource
方法模拟获取资源的过程,返回一个Closeable
,而Closeable
的close
方法在这里用Lambda表达式实现,表示关闭资源的操作。通过传递不同的Consumer
,可以执行不同的资源操作。这种模式在需要确保资源被正确关闭的情况下非常有用。