Yura February 2016

What "->" means in Java

I'm the beginner in Java simple things are new to me. Besides my level google doesn't want to search such keywords like "->" :)

I found it here. So I think this code is correct.

Please help me to understand what does this expression mean?

firstNameCol.setOnEditCommit(
        (CellEditEvent<Person, String> t) -> {
            ((Person) t.getTableView().getItems().get(
                    t.getTablePosition().getRow())
                    ).setFirstName(t.getNewValue());

Answers


emory February 2016

That is a lambda expression - https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html.

It is new in java 8.

When an interface has only one method and is annotated with @FunctionalInterface then it is a functional interface. This allows you to use the "->" syntax to bypass a lot of verbose boilerplate code.

You can replace

btn.setOnAction(new EventHandler<ActionEvent>() {

    @Override
    public void handle(ActionEvent event) {
        System.out.println("Hello World!");
    }
});

with

btn.setOnAction(
  event -> System.out.println("Hello World!")
);

Post Status

Asked in February 2016
Viewed 1,015 times
Voted 5
Answered 1 times

Search




Leave an answer