Luckylukee
Luckylukee

Reputation: 595

Lambda function in Java 8 with no parameter and returning value

I want to convert a simple Java function to a lambda 8 function without any parameter, and then call it:

public int getMissing() {
  return 0;
}

how to convert above to java8 lambda format?

Upvotes: 16

Views: 16928

Answers (6)

Grant Park
Grant Park

Reputation: 1044

Define the following:

public interface Function<T> {
    public T apply();
}

With this, you can do something like

methodThatAcceptsFunction(() -> { getMissing(); });

Upvotes: 0

Grzegorz Piwowarek
Grzegorz Piwowarek

Reputation: 13803

You do not really convert methods into lambdas directly. Lambdas are more-or-less implementations of Functional Interfaces created on the fly without the overhead of the classic anonymous inner function approach.

So, if you want to pass it around as a lambda, you need to find a matching Functional Interface and assign a lambda to it.

In this case, you have a method without parameters that returns an int and one of the possible choices would be to use IntSupplier:

IntSupplier supplier = () -> 0;

and now, you can call it by doing:

supplier.getAsInt()

If you want to return a boxed Integer, you would need to use a generic Supplier<T>:

Supplier<Integer> supplier = () -> 0;
supplier.get(); // 0

Upvotes: 3

Yanjing Wang
Yanjing Wang

Reputation: 46

Lambda solves issues that with anonymous classes and interfaces that hava one method. Java8 has predefined functional interfaces(Function,Predicate,Consumer) which all accept parameters. you can define custom functional interface that has no paramter.

Upvotes: 0

Viet
Viet

Reputation: 3409

Your case is similar with Supplier in Java 8

 Supplier<Integer> supplier = () -> 0;
 System.out.println(supplier.get());

Upvotes: 24

Kannaiyan
Kannaiyan

Reputation: 13035

To have a lambda function you don't need to input anything or output anything back.

The entry point of the java code needs to be of certain format as described in the documentation.

http://docs.aws.amazon.com/lambda/latest/dg/get-started-step4-optional.html

You can use any code converter to convert java code, follow the instructions above for entry point, upload and call an external url (via api gateway) or test with the test button in aws console.

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201467

It isn't clear what you intend to do with that value, but a generator has the form () -> Int - something like,

IntStream.generate(() -> 0).limit(1).forEach(System.out::println);

If you omit the limit(1) then you will get an infinite number of zeros, if you need to preserve order use forEachOrdered (instead of forEach).

Upvotes: 1

Related Questions