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.
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)
| 归档时间: |
|
| 查看次数: |
24790 次 |
| 最近记录: |