java8 四个冒号_java8 :: 用法 (JDK8 双冒号用法)

特性

jdk8中使用了::的用法。就是把方法当做参数传到stream内部,使stream的每个元素都传入到该方法里面执行一下,双冒号运算就是Java中的[方法引用],[方法引用]的格式是:

类名::方法名

注意此处没有()。

案例:

表达式:

person -> person.getAge();

使用双冒号:

Person::getAge

表达式:

new HashMap<>()

使用双冒号:

HsahMap :: new

部分代码案例

未使用双冒号

public class MyTest {

public static void main(String[] args) {

List a1 = Arrays.asList("a", "b", "c");

for (String a : a1) {

printValur(a);

};

a1.forEach(x -> MyTest.printValur(x));

}

public static void printValur(String str) {

System.out.println("print value : " + str);

}

}

使用后

a1.forEach(MyTest::printValur);

Consumer consumer = MyTest::printValur;

a1.forEach(x -> consumer.accept(x));

未使用双冒号:

List list = a1.stream().map(x -> x.toUpperCase()).collect(Collectors.toList());

System.out.println(list.toString());

使用双冒号:

ArrayList collect = a1.stream().map(String::toUpperCase).collect(Collectors.toCollection(ArrayList::new));

System.out.println(collect.toString());

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值