1

I'm very new to Lambda, and I would like to have a Generic class done so like a non-generic class. Take for example the Runnable, it isn't generic:

Runnable runnable = () -> {
    // code here
}

And I had a Generic class, how would I do it in Lambda just like I can with a non-generic class?

MyGenericClass<T> generic = ...
5
  • Runnable is not generic Commented Jul 14, 2014 at 15:43
  • I know it's not, but what would I do for lambda if a class had a generic type? Does lambda even allow me to do that? Commented Jul 14, 2014 at 15:44
  • 1
    Yes. The lambda type is a FunctionalInterface (though the annotation itself is not mandatory). See Function<> or Predicate<> for examples of easy-to-understand generic functional interfaces. Commented Jul 14, 2014 at 15:48
  • Lambdas which implement generic functional interfaces are declared the same way. Runnable doesn't have any type parameters. What are you trying to achieve? You may need to use Callable. Commented Jul 14, 2014 at 15:51
  • You can find some info about target typing in the lambda expressions tutorial Commented Jul 14, 2014 at 15:57

2 Answers 2

4

Lambdas use generics and type inference heavily. So much so that type inference was add to Java 8 to make the syntax more readable.

Let me give you an example

// this adds a dynamic reference to this method
Predicate<String> isEmpty = String::isEmpty;

or

// this creates a new lambda static method and 
// creates a dynamic reference to that method
Predicate<String> isEmpty = s -> s.isEmpty();

or

Predicate<String> containsX = s -> s.contains("X");

These are used by Stream.filter()

Sign up to request clarification or add additional context in comments.

Comments

1

There's an example here where they use:

Callable<String> c = () -> "Hello from Callable";

and

List<Employee> list = new ArrayList<Employee>();
Collections.sort(list,
        (x, y) -> x.getLastName().compareTo(y.getLastName()));

Is that what you are looking for?

Essentially - the lambdas in java 8 take the type intuition that was introduced in Java 7 to the nth degree. It is really quite astonishing how effective it is in working out the types of complex expressions.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.