在Java语法中::的含义

six*_*eet 25 java syntax java-8

以下代码中::的含义是什么?

Set<String> set = people.stream()
                        .map(Person::getName)
                        .collect(Collectors.toCollection(TreeSet::new));
Run Code Online (Sandbox Code Playgroud)

Era*_*ran 36

这是方法参考.在Java 8中添加.

TreeSet::new指的是默认构造函数TreeSet.

一般A::B指的是B课堂上的方法A.

  • +1,他们接下来会想到什么?字符串切换也许......与方法的接口...... (3认同)
  • @Bathsheba,我正在指责操作员超载. (2认同)
  • @ChiefTwoPencils特别是如果他们也将`,`定义为运算符. (2认同)

jbu*_*483 19

::被称为方法参考.它基本上是对单个方法的引用.即它通过名称引用现有方法.

Method reference using ::是一个便利的运营商.

方法引用是属于Java lambda表达式的特性之一.方法引用可以使用通常的lambda表达式语法格式表示–>,以使其更简单,::可以使用运算符.

例:

public class MethodReferenceExample {
    void close() {
        System.out.println("Close.");
    }

    public static void main(String[] args) throws Exception {
        MethodReferenceExample referenceObj = new MethodReferenceExample();
        try (AutoCloseable ac = referenceObj::close) {
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

所以,在你的例子中:

Set<String> set = people.stream()
                        .map(Person::getName)
                        .collect(Collectors.toCollection(TreeSet::new));
Run Code Online (Sandbox Code Playgroud)

正在调用/创建一个"新"树集.

Contstructor Reference的类似示例是:

class Zoo {
    private List animalList;
    public Zoo(List animalList) {
        this.animalList = animalList;
        System.out.println("Zoo created.");
    }
}

interface ZooFactory {
    Zoo getZoo(List animals);
}

public class ConstructorReferenceExample {

    public static void main(String[] args) {
        //following commented line is lambda expression equivalent
        //ZooFactory zooFactory = (List animalList)-> {return new Zoo(animalList);};    
        ZooFactory zooFactory = Zoo::new;
        System.out.println("Ok");       
        Zoo zoo = zooFactory.getZoo(new ArrayList());
    }
}
Run Code Online (Sandbox Code Playgroud)


Mis*_*sha 13

此上下文中的Person :: getName是简写 (Person p) -> p.getName()

请参阅JLS第15.13节中的更多示例和详细说明