PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, November 4, 2022

[FIXED] How to pass a Java 8 lambda with a single parameter

 November 04, 2022     java, java-8, lambda     No comments   

Issue

I want to simply pass a lambda (chunk of code) and execute it when I need to. How do I implement the method executeLambda(...) in the code below (as well what is the method signature):

public static void main(String[] args)
{
    String value = "Hello World";
    executeLambda(value -> print(value));
}

public static void print(String value)
{
    System.out.println(value);
}

public static void executeLambda(lambda)
{
    someCode();
    lamda.executeLambdaCode();
    someMoreCode();
}

Solution

Your lambda takes one parameter, but you only pass the lambda to executeLambda, not the value. If you want the lambda to capture the local variable, don't write it taking a parameter, but if you do really want it to take one parameter, you would write it like this:

import java.util.function.Consumer;

public static void main(String[] args) {
    String message = "Hello World";
    executeLambda(message, value -> print(value));
}

public static void executeLambda(String value, Consumer<String> lambda) {
    lambda.accept(value);
}

If you want it to capture the value, then use Runnable, write the lambda as () -> print(value), and call it like runnable.run().



Answered By - David Conrad
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing