lambda表达式双冒号使用条件_java_java基础_lambda表达式双冒号用法

过于基础,就不废话了,实验代码如下:

package com.demo;

import java.util.Arrays;

import java.util.List;

import java.util.function.BiPredicate;

import java.util.function.Function;

public class DoubleColonTest {

String str;

public DoubleColonTest(String str) {

this.str = str;

}

public static void main(String[] args) {

/**

* :: 双冒号表示方法引用

* 案例一:对象::实例方法

* public interface Consumer {

* void accept(T t);

* }

*

* public void println(Object x) {

* 此处省略

* }

*/

List list = Arrays.asList(1, 2, 3);

list.forEach(System.out::println);

System.out.println("------------分割线------------------");

/**

* 案例二:类::实例方法

* public interface BiPredicate {

* boolean test (T t, U u);

* }

*

* public boolean equals(Object obj) {

* return (this == obj);

* }

*/

System.out.println(testEquals(Object::equals, "a", "a"));

System.out.println("------------分割线------------------");

/**

* 案例三:类::静态方法

* public interface Function {

* R apply (T t);

* }

*

* public static int abs(int a) {

* return (a < 0) ? -a : a;

* }

*

* 总结:当方法的参数类型,参数个数,参数顺序与接口方法一致时,可以使用双冒号

* java内置了许多函数式接口,在java.util.function下。感兴趣的同学可以看下

*/

System.out.println(testAbs(Math::abs, -10));

System.out.println("------------分割线------------------");

/**

* 双冒号表示构造器引用,当构造器的参数类型,参数个数,参数顺序与接口方法一致时,可以使用双冒号

* public interface Function {

* R apply (T t);

* }

*

* public DoubleColonTest(String str) {

* this.str = str;

* }

*

*/

Function testFunction = DoubleColonTest::new;

testConstructor(testFunction, "hello world");

testConstructor(DoubleColonTest::new, "hello the world");

System.out.println("------------分割线------------------");

/**

* 双冒号表示数组引用,当方法的参数类型,参数个数,参数顺序与接口方法一致时,可以使用双冒号

* public interface Function {

* R apply (T t);

* }

*

* Integer [] integers = new Integer[t];

*/

testArray(Integer[]::new, 10);

}

public static boolean testEquals(BiPredicate biPredicate, Object obj1, Object obj2) {

return biPredicate.test(obj1, obj2);

}

public static Integer testAbs(Function function, Integer integer) {

return function.apply(integer);

}

public static void testConstructor(Function function, String str) {

DoubleColonTest test = function.apply(str);

System.out.println(test.str);

}

public static void testArray(Function function, Integer length) {

Integer[] apply = function.apply(length);

System.out.println(apply.length);

}

}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值