How can we pass a function as a parameter in java?

0 votes
Is it possible to do so?
Jun 27, 2018 in Java by Akrati
• 960 points
23 views

2 answers to this question.

0 votes

You can probably use the below code:

public T myMethod(Callable<T> func) 
{
    return func.call();
}
answered Jun 27, 2018 by Akrati
• 3,150 points
0 votes

Java 8 and above

Using Java 8+ lambda expressions, if you have a class or interface with only a single method, for example:

public interface MyInterface {
    String doSomething(int param1, String param2);
}

then anywhere where MyInterface is used, you can substitute a lambda expression:

class MyClass {
    public MyInterface myInterface = (p1, p2) -> { return p2 + p1; };
}
answered Aug 28, 2018 by Daisy
• 8,040 points

Related Questions In Java

0 votes
1 answer

How can we split a comma separated String in Java?

String str = "..."; // write the ...READ MORE

answered Jun 12, 2018 in Java by parth295
• 4,600 points
44 views
0 votes
1 answer

How can we encrypt a String in Java?

Let's assume the bytes to encrypt are ...READ MORE

answered Oct 26, 2018 in Java by Sushmita
• 6,840 points
13 views
0 votes
1 answer

How can I convert a String variable to a primitive int in Java

You can convert a String to int by using a function: int ...READ MORE

answered Apr 12, 2018 in Java by sharth
• 3,320 points
83 views
0 votes
4 answers

How can we define global variables in java?

class G { static String globalVar ...READ MORE

answered Jan 29 in Java by zemiak
2,297 views
0 votes
1 answer

What is a name function in JavaScript & how to define it?

A named function declares a name as ...READ MORE

answered Mar 6 in Others by Frankie
• 9,810 points
23 views
+5 votes
3 answers

How to execute a python file with few arguments in java?

You can use Java Runtime.exec() to run python script, ...READ MORE

answered Mar 27, 2018 in Java by DragonLord999
• 8,380 points

edited Nov 6, 2018 by Omkar 6,033 views
0 votes
1 answer

How to handle drop downs using Selenium WebDriver in Java

First, find an XPath which will return ...READ MORE

answered Mar 27, 2018 in Selenium by nsv999
• 5,050 points
1,587 views
0 votes
1 answer

What are the differences between getText() and getAttribute() functions in Selenium WebDriver?

See, both are used to retrieve something ...READ MORE

answered Apr 5, 2018 in Selenium by nsv999
• 5,050 points
4,261 views
0 votes
1 answer

How can we resolve ClassNotFoundException in Java?

Your classpath is broken. Depending on how you ...READ MORE

answered May 22, 2018 in Java by Akrati
• 3,150 points
37 views
0 votes
1 answer

How can we add leading zeros to the number in Java?

To add zeros to a number, we ...READ MORE

answered May 25, 2018 in Java by Akrati
• 3,150 points
141 views