javaaccept()⽤法_java8::⽤法(JDK8双冒号⽤法)JDK8中有双冒号的⽤法,就是把⽅法当做参数传到stream内部,使stream的每个元素都传⼊到该⽅法⾥⾯执⾏⼀下。
代码其实很简单:
想啦
以前的代码⼀般是如此的:
public class AcceptMethod {
public static void printValur(String str){
System.out.println("print value : "+str);
}
public static void main(String[] args) {
List al = Arrays.asList("a","b","c","d");
for (String a: al) {
AcceptMethod.printValur(a);
}
自发绿豆芽//下⾯的for each循环和上⾯的循环是等价的
al.forEach(x->{
开学安全第一课教案
AcceptMethod.printValur(x);
});
}
}
现在JDK双冒号是:
土木工程生产实习报告
public class MyTest {
public static void printValur(String str){
System.out.println("print value : "+str);
两个月宝宝吃手
}
public static void main(String[] args) {
List al = Arrays.asList("a", "b", "c", "d");
部队标语al.forEach(AcceptMethod::printValur);
//下⾯的⽅法和上⾯等价的
Consumer methodParam = AcceptMethod::printValur; //⽅法参数
al.forEach(x -> methodParam.accept(x));//⽅法执⾏accept
}
}
上⾯的所有⽅法执⾏玩的结果都是如下:
经典小说print value : a
print value : b
print value : c
print value : d
在JDK8中,接⼝Iterable 8中默认实现了forEach⽅法,调⽤了 JDK8中增加的接⼝Consumer内的accept⽅法,执⾏传⼊的⽅法参数。JDK源码如下:
/*** Performs the given action for each element of the {@codeIterable}
* until all elements have been procesd or the action throws an
* exception. Unless otherwi specified by the implementing class,
* actions are performed in the order of iteration (if an iteration order
* is specified). Exceptions thrown by the action are relayed to the
* caller.
*
* @implSpec
*
The default implementation behaves as if:
*
{@code* for (T t : this)
* action.accept(t);
* }
*
*@paramaction The action to be performed for each element
*@throwsNullPointerException if the specified action is null
*@since1.8*/
default void forEach(Consumer super T>action) {
action.accept(t);
}
小孩能拔罐吗
}
另外补充⼀下,JDK8改动的,在接⼝⾥⾯可以有默认实现,就是在接⼝前加上default,实现这个接⼝的函数对于默认实现的⽅法可以不⽤再实现了。类似的还有static⽅法。现在这种接⼝除了上⾯提到的,还有BiConsumer,BiFunction,BinaryOperation等,在
java.util.function包下的接⼝,⼤多数都有,后缀为Supplier的接⼝没有和别的少数接⼝。