Aadish Patodi Aadish Patodi - 4 months ago 12
Java Question

Unknown syntax in Java Code

I am going through Building REST Services with Spring Tutorial at https://spring.io/guides/tutorials/bookmarks/

And I am stuck at a point. In the

class Application
, there is this spooky piece of code:

return (evt) -> Arrays.asList(
"jhoeller,dsyer,pwebb,ogierke,rwinch,mfisher,mpollack,jlong".split(","))
.forEach(
a -> {
Account account = accountRepository.save(new Account(a,
"password"));
bookmarkRepository.save(new Bookmark(account,
"http://bookmark.com/1/" + a, "A description"));
bookmarkRepository.save(new Bookmark(account,
"http://bookmark.com/2/" + a, "A description"));
});


I seriously have no idea whats going on there. From where
evt
came, there is no relevant import. And what does
->
operator do in Java. I have never used this operator in Java. Is there any operator as such, first of all?

Even my eclipse says the same thing that


evt cannot be resolved to a variable


Nobody seems to ask similar question on internet, I searched a lot. Am I missing something?

Answer

This is Java 8 syntax (a lambda expression, i.e. sort of an anonymous function), and from your descriptions you seem not to be familiar with Java 8. You are probably still running Java 7 or older. You can check your Java version using the java -version command.

About evt: It is defined within the lambda expression, which is roughly equivalent to this:

new Consumer<Event>() {
    @Override
    public void accept(Event evt) {
        for (String a: Arrays.asList("jhoeller,dsyer,pwebb,ogierke,rwinch,mfisher,mpollack,jlong".split(",")) {
            Account account = accountRepository.save(new Account(a,
                    "password"));
            bookmarkRepository.save(new Bookmark(account,
                    "http://bookmark.com/1/" + a, "A description"));
            bookmarkRepository.save(new Bookmark(account,
                    "http://bookmark.com/2/" + a, "A description"));
        }
    }
}

If you want to run that code, you will have to download and install a new Version of Java. If you are already using Java 8, then you probably have to configure your system properly.

From your comments I gather that you are using Eclipse. First, you have to use an Eclipse that can handle Java 8 (Luna or newer), then select the correct JDK in Eclipse (Preferences -> Java -> Installed JREs), and also set the source compatibility level of your project to Java 8 (Project's Properties -> Java Compiler -> JDK Compliance).

Comments