thiaoqueen

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

  类名::方法名 

注意此处没有()。

案例:

表达式:

person -> person.getAge();

使用双冒号:

Person::getAge

表达式:

new HashMap<>()

使用双冒号:

HsahMap :: new

部分代码案例

未使用双冒号

public class MyTest {
    public static void main(String[] args) {
        List<String> 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<String> consumer = MyTest::printValur;
        a1.forEach(x -> consumer.accept(x));

未使用双冒号:

     List<String> list = a1.stream().map(x -> x.toUpperCase()).collect(Collectors.toList());
     System.out.println(list.toString());

使用双冒号:

        ArrayList<String> collect = a1.stream().map(String::toUpperCase).collect(Collectors.toCollection(ArrayList::new));
        System.out.println(collect.toString());

 

分类:

技术点:

相关文章:

  • 2021-12-17
  • 2021-10-29
  • 2020-07-14
  • 2019-08-12
  • 2021-12-04
  • 2021-12-09
  • 2021-11-18
  • 2021-09-10
猜你喜欢
  • 2021-11-12
  • 2021-10-19
  • 2021-11-03
  • 2021-12-19
  • 2019-08-18
  • 2021-11-13
相关资源
相似解决方案