java.util.function
Consumer 接收T对象,不返回值
作用:
消费某个对象
Iterable接口的forEach方法需要传入Consumer,大部分集合类都实现了该接口,用于返回Iterator对象进行迭代。
Iterable forEach 函数:
default void forEach(Consumer super T> action) {
Objects.requireNonNull(action);
for (T t : this) {
action.accept(t);
}
}
使用场景:
forEach 自定义处理的逻辑代码,灵活多变
demo
public static void main(String[] args) {
Consumer methodParam = HelloHandler::staticMethod;
Consumer methodParam1 = HelloHandler::staticMethod;
Consumer methodParam2 = methodParam.andThen(methodParam1);
methodParam2.accept(1);
BiConsumer biConsumer = HelloHandler::normalMethod;
// methodParam1.accept(2);
// HelloHandler helloHandler = new HelloHandler();
//
// Function function = new HelloHandler()::normalMethod;
// System.out.println( function.apply(1));
// Consumer methodParam1 = helloHandler::normalMethod;
List list = new ArrayList<>();
list.add("a");
list.add("b");
list.add("c");
list.forEach(new DemoConsumer());
}
static class DemoConsumer implements Consumer{
@Override
public void accept(String s) {
//处理业务逻辑代码
System.out.println("s = [" + s + "]");
}
}
这样逻辑代码就分离出来了
可以简化为 lambda 表达式:
list.forEach(c->{
//处理业务逻辑代码
System.out.println("c = [" + c + "]");
});