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

2022-10-16,,,,

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的接口没有和别的少数接口。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对的支持。

《java8中:: 用法示例(JDK8双冒号用法).doc》

下载本文的Word格式文档,以方便收藏与打印。