java.util.function
Consumer<T> 接收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<Integer> methodParam = HelloHandler::staticMethod;
Consumer<Integer> methodParam1 = HelloHandler::staticMethod;
Consumer<Integer> methodParam2 = methodParam.andThen(methodParam1);
methodParam2.accept(1);
BiConsumer<HelloHandler,Integer> biConsumer = HelloHandler::normalMethod;
// methodParam1.accept(2);
// HelloHandler helloHandler = new HelloHandler();
//
// Function<Integer,Integer> function = new HelloHandler()::normalMethod;
// System.out.println( function.apply(1));
// Consumer<Integer> methodParam1 = helloHandler::normalMethod;
List<String> list = new ArrayList<>();
list.add("a");
list.add("b");
list.add("c");
list.forEach(new DemoConsumer());
}
static class DemoConsumer implements Consumer<String>{
@Override
public void accept(String s) {
//处理业务逻辑代码
System.out.println("s = [" + s + "]");
}
}
这样逻辑代码就分离出来了
可以简化为 lambda 表达式:
list.forEach(c->{
//处理业务逻辑代码
System.out.println("c = [" + c + "]");
});
转载于:https://blog.51cto.com/5013162/2380932