欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

java8中:: 用法示例(JDK8双冒号用法)

时间:2021-02-12 08:50:59|栏目:JAVA代码|点击:

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 {@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
 * <p>The default implementation behaves as if:
 * <pre>{@code
 * for (T t : this)
 *  action.accept(t);
 * }</pre>
 *
 * @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的接口没有和别的少数接口。

总结

上一篇:java使用Jsoup连接网站超时的解决方法

栏    目:JAVA代码

下一篇:Matlab及Java实现小时钟效果

本文标题:java8中:: 用法示例(JDK8双冒号用法)

本文地址:http://www.codeinn.net/misctech/61715.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有