在Java语法中::的含义

时间:2014-11-19 11:16:21

标签: java syntax java-8

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

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

3 个答案:

答案 0 :(得分:30)

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

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

一般情况A::B引用课程B中的方法A

答案 1 :(得分:15)

::称为方法参考。它基本上是对单个方法的引用。即它是指按名称的现有方法。

Method reference using ::便利运算符。

方法参考是属于Java lambda expressions的功能之一。可以使用–>使用通常的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) {
        }
    }
}

因此,在您的示例中:

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

调用/创建'新'树集。

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());
    }
}

答案 2 :(得分:9)

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

的简写

JLS section 15.13

中查看更多示例和详细说明