List<String> list = Arrays.asList("真","可","爱");
list.forEach(item-> System.out.println(item));
list.forEach(new Consumer<String>() {
@Override
public void accept(String s) {
System.out.println(s);
}
});
list.forEach(System.out::print);
//这就是语法糖
//真可爱真可爱
@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); };
}
}
Iterable.class
default void forEach(Consumer<? super T> action) {
Objects.requireNonNull(action);
for (T t : this) {
action.accept(t);
}
}
public interface Supplier<T> {
/**
* Gets a result.
*
* @return a result
*/
T get();
}
所以lambda一个用法是避免提供匿名内部类,new Supplier(){ ...}直接被()-> new StringBuilder代替,再一步可以简化为方法引用:StringBuilder::new.