What does the arrow operator, '->', do in Java?

丶灬走出姿态 提交于 2019-12-16 22:16:26

问题


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();
});

Details: Java 6, Apache Commons Collection, IntelliJ 12

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();
    }
});

回答1:


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 actual expression (right side).




回答2:


I believe, this arrow exists because of your IDE. IntelliJ IDEA does such thing with some code. This is called code folding. You can click at the arrow to expand it.




回答3:


This one is useful as well when you want to implement a functional interface

Runnable r = ()-> System.out.print("Run method");

is equivalent to

Runnable r = new Runnable() {
            @Override
            public void run() {
                System.out.print("Run method");
            }
        };



回答4:


It's a lambda expression.

It means that, from the listOfCars, arg0 is one of the items of that list. With that item he is going to do, hence the ->, whatever is inside of the brackets.

In this example, he's going to return a list of cars that fit the condition

Car.SEDAN == ((Car)arg0).getStyle();



回答5:


New Operator for lambda expression added in java 8

Lambda expression is the short way of method writing.
It is indirectly used to implement functional interface

Primary Syntax : (parameters) -> { statements; }

There are some basic rules for effective lambda expressions writting which you should konw.



来源:https://stackoverflow.com/questions/15146052/what-does-the-arrow-operator-do-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!