java accept()用法_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);});}}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}}上面的所有方法执行玩的结果都是如下:1234print value : aprint value : bprint value : cprint value : d  在JDK8中,接口Iterable 8中默认实现了forEach方法,调用了 JDK8中增加的接口Consumer内的accept方法,执行传入的方法参数。JDK源码如下:12345678910111213141516171819202122232425/**     * Performs the given action for each element of the {@code Iterable}     * until all elements have been processed or the action throws an     * exception.  Unless otherwise 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);     * }
     *     * @param action The action to be performed for each element     * @throws NullPointerException if the specified action is null     * @since 1.8     */default void forEach(Consumer super T> action) {Objects.requireNonNull(action);for (T t : this) {action.accept(t);}}

JDK8改动的,在接口里面可以有默认实现,就是在接口前加上default,实现这个接口的函数对于默认实现的方法可以不用再实现了。类似的还有static方法。现在这种接口除了上面提到的,还有BiConsumer,BiFunction,BinaryOperation等,在java.util.function包下的接口,大多数都有,后缀为Supplier的接口没有和别的少数接口。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值