Java 中的箭头运算符“->"有什么作用? [英] What does the arrow operator, '->', do in Java?
问题描述
在搜索一些代码时,我遇到了箭头运算符,它到底是做什么的?我以为 Java 没有箭头运算符.
While hunting through some code I came across the arrow operator, what exactly does it do? I thought Java did not have an arrow operator.
return (Collection<Car>) CollectionUtils.select(listOfCars, (arg0) -> {
return Car.SEDAN == ((Car)arg0).getStyle();
});
详细信息:Java 6、Apache Commons Collection、IntelliJ 12
Details: Java 6, Apache Commons Collection, IntelliJ 12
更新/答案:事实证明,IntelliJ 12 支持 Java 8,它支持 lambda,并且正在折叠"谓词并将它们显示为 lambda.下面是展开"的代码.
Update/Answer: It turns out that IntelliJ 12 supports Java 8, which supports lambdas, and is "folding" Predicates and displaying them as lambdas. Below is the "un-folded" code.
return (Collection<Car>) CollectionUtils.select(listOfCars, new Predicate() {
public boolean evaluate(Object arg0) {
return Car.SEDAN == ((Car)arg0).getStyle();
}
});
推荐答案
这是新的 lambda 表达式语法的一部分,将在 Java 8 中引入.有几个在线教程可以掌握它,这里是一个链接到一个.基本上,->
将参数(左侧)与实现(右侧)分开.
That's part of the syntax of the new lambda expressions, to be introduced in Java 8. There are a couple of online tutorials to get the hang of it, here's a link to one. Basically, the ->
separates the parameters (left-side) from the implementation (right side).
使用 lambda 表达式的一般语法是
The general syntax for using lambda expressions is
(参数)->{ Body }
其中 ->
分隔参数和 lambda 表达式主体.
(Parameters) -> { Body }
where the ->
separates parameters and lambda expression body.
参数用括号括起来,这与方法相同,而且 lambda 表达式主体是用大括号括起来的代码块.
The parameters are enclosed in parentheses which is the same way as for methods and the lambda expression body is a block of code enclosed in braces.
这篇关于Java 中的箭头运算符“->"有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!