Java语法中::的含义是什么?

44

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

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

68

这是方法引用(Method Reference)。它在Java 8中被添加。

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

一般而言,A::B指的是类A中的方法B


3
+1,他们接下来会想出什么?也许是字符串切换……带有方法的接口…… - Bathsheba
2
@Bathsheba,我为运算符重载祈祷。 - ChiefTwoPencils
2
@ChiefTwoPencils 特别是如果他们还将“,”定义为运算符。 - Marko Topolnik
@Bathsheba 自从1.8版本以后,接口中可用默认方法和静态方法。 - raviraja

37

:: 被称为方法引用,它基本上是对单个方法的引用。也就是说,它通过名称引用现有方法。

使用 :: 进行方法引用 是一个方便操作符。

方法引用是 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) {
        }
    }
}

所以,在你的例子中:
Set<String> set = people.stream()
                        .map(Person::getName)
                        .collect(Collectors.toCollection(TreeSet::new));

调用/创建 'new' treeset.
构造器引用的一个类似示例是:
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());
    }
}

29

在这个上下文中,Person::getName是(Person p) -> p.getName()的简写。

更多例子和详细解释请参见JLS第15.13节


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接