以下代码中::的含义是什么?
Set<String> set = people.stream()
.map(Person::getName)
.collect(Collectors.toCollection(TreeSet::new));
这是方法引用(Method Reference)。它在Java 8中被添加。
TreeSet::new
指的是TreeSet
类的默认构造函数。
一般而言,A::B
指的是类A
中的方法B
。
::
被称为方法引用,它基本上是对单个方法的引用。也就是说,它通过名称引用现有方法。
使用 :: 进行方法引用
是一个方便操作符。
方法引用是 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));
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());
}
}