Java的Collection可以通过迭代器、增强for、forEach遍历,而forEach遍历中又可以使用lambda表达式简化代码,现在从源码上分析Lambda表达式遍历的原理。
正常使用forEach遍历示例
Collection<String> col = new ArrayList<>();
.forEach(new Consumer<String>(){
col@Override
//s依次表示集合中每一个元素
public void accept(String s) {
System.out.println(s);
}
});
forEach()源码
default void forEach(Consumer<? super T> action) {
.requireNonNull(action);
Objectsfor (T t : this) {
.accept(t);
action}
}
可以看到是参数是一个Consumer<? super T> action
,之后使用增强for遍历了集合内部的元素
Consumer<? super T>源码
@FunctionalInterface
public interface Consumer<T> {
/**
* Performs this operation on the given argument.
*
* @param t the input argument
*/
void accept(T t);
/**
* Returns a composed {@code Consumer} that performs, in sequence, this
* operation followed by the {@code after} operation. If performing either
* operation throws an exception, it is relayed to the caller of the
* composed operation. If performing this operation throws an exception,
* the {@code after} operation will not be performed.
*
* @param after the operation to perform after this operation
* @return a composed {@code Consumer} that performs in sequence this
* operation followed by the {@code after} operation
* @throws NullPointerException if {@code after} is null
*/
default Consumer<T> andThen(Consumer<? super T> after) {
.requireNonNull(after);
Objectsreturn (T t) -> { accept(t); after.accept(t); };
}
}
可以看到是一个接口,并且标注了
@FunctionalInterface
,可以用lambda表达式来充当这个接口的实现类
使用lambda后的代码
.forEach(s -> System.out.println(s)); col
可以发现大大简化了