【发布时间】:2014-11-19 11:16:21
【问题描述】:
下面代码中::是什么意思?
Set<String> set = people.stream()
.map(Person::getName)
.collect(Collectors.toCollection(TreeSet::new));
【问题讨论】:
下面代码中::是什么意思?
Set<String> set = people.stream()
.map(Person::getName)
.collect(Collectors.toCollection(TreeSet::new));
【问题讨论】:
这是方法参考。在 Java 8 中添加。
TreeSet::new指的是TreeSet的默认构造函数。
一般A::B指的是A类中的方法B。
【讨论】:
, 定义为运算符。
:: 称为方法参考。它基本上是对单一方法的引用。即它通过名称引用现有方法。
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));
正在调用/创建一个“新”树集。
构造函数引用的类似示例是:
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());
}
}
【讨论】:
Person::getName 在此上下文中是 (Person p) -> p.getName() 的简写
在JLS section 15.13查看更多示例和详细解释
【讨论】: