Napoleon
Napoleon

Reputation: 19

Having trouble understanding Java 8 's Function<>

As I'm learning how to use various new tools, I ran upon this syntax (Function x -> ...) which I'm having trouble understanding, and I'd love for someone to write equivalent code if possible so that I can understand it better.

Function<String, HashSet<String>> asSet = (String x) ->
      new HashSet<String>() {{
        do_something(x);
      }};

Any block of code using more traditional syntax and not that weird Function would be greatly appreciated and useful in helping me better my understanding of Java!

Upvotes: 0

Views: 84

Answers (3)

Yousef Khaled
Yousef Khaled

Reputation: 21

This syntax is called Lambda Expressions it's used to simplify implementing Functional Interfaces.

Functional Interfaces: are interfaces with one function to implement for example you can write:

// Java program to demonstrate functional interface

class Test {
    public static void main(String args[]) {
        // create anonymous inner class object 
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("New thread created");
            }
        }).start();
    }
}

or

// Java program to demonstrate Implementation of
// functional interface using lambda expressions

class Test {
    public static void main(String args[]) {

        // lambda expression to create the object 
        new Thread(() - > {
            System.out.println("New thread created");
        }).start();
    }
}

Upvotes: 0

mle
mle

Reputation: 2542

Very basically and without explaining the advantages of using Functions you can imagine your function to be an analogy of:

HashSet<String> anonymousMethod(String x) {
    return doSomething(x);
}

...which resides anonymously in your function object.

Upvotes: 0

Ruslan
Ruslan

Reputation: 6290

It can be replaced with anonymous class:

Function<String, HashSet<String>> asSet = new Function<>() {
    @Override
    public HashSet<String> apply(String s) {
        return new HashSet<>() {{
            do_something(s);
        }};
    }
};

You just implement apply method from Function which is functional interface:

Note that instances of functional interfaces can be created with lambda expressions, method references, or constructor references.

See more What is use of Functional Interface in Java 8?

Upvotes: 1

Related Questions