Java pass method as method parameter

Programming for beginners

From Java8 onwards, you can pass a method as argument using lambda expressions and method references. To go in more details, let me explain about Functional interfaces.

A Functional interface is the interface, which contains only one abstract method. Java 8 uses functional interfaces to implement lambda expressions.

Lambda expressions is a new feature included in Java SE 8. Lambda Expressions provide a way to represent functional interface using an expression.

package com.sample.app; import java.io.IOException; public class App < public interface Arithmetic < int operation(int var1, int var2); > public static void main(String args[]) throws IOException < Arithmetic add = (int a, int b) -> < return (a + b); >; Arithmetic subtract = (int a, int b) -> < return (a - b); >; Arithmetic multiply = (int a, int b) -> < return (a * b); >; Arithmetic divide = (int a, int b) -> < return (a / b); >; Arithmetic remainder = (int a, int b) -> < return (a % b); >; System.out.println("Sum of 11 and 5 is " + add.operation(11, 5)); System.out.println("Subtraction of 11 and 5 is " + subtract.operation(11, 5)); System.out.println("Multiplication of 11 and 5 is " + multiply.operation(11, 5)); System.out.println("Division of 11 and 5 is " + divide.operation(11, 5)); System.out.println("Remainder of 11 and 5 is " + remainder.operation(11, 5)); > >
Sum of 11 and 5 is 16 Subtraction of 11 and 5 is 6 Multiplication of 11 and 5 is 55 Division of 11 and 5 is 2 Remainder of 11 and 5 is 1

Источник

Pass a Method as a Parameter in Java

Pass a Method as a Parameter in Java

  1. Pass a Method as a Parameter by Using the lambda Function in Java
  2. Pass a Method as a Parameter to a Custom Method in Java
  3. Pass a Method as a Parameter Using the Method Reference in Java

This tutorial introduces the passing of a method as a parameter in Java. To help you understand this topic further, we’ve included example codes.

There’s no concept of a passing method as a parameter in Java from scratch. However, we can achieve this by using the lambda function and method reference in Java 8. So in this article, we’ll focus more on these two topics to pass a method as a parameter.

The lambda function or lambda expression is a concept that was introduced in Java 8. It’s a concise way to write a function by following the functional style approach. Since Java and Java 8 are considered Object-Oriented Languages, they support the functional approach to write the code.

Читайте также:  Чем отличается elif от else python

Pass a Method as a Parameter by Using the lambda Function in Java

This is a simple example of lambda, where we are using it to iterate the ArrayList elements. Notice that we’re passing the lambda function to the forEach() method of the Iterable interface. The ArrayList class implements the Iterable interface.

So this is how we can pass a method(lambda function) as a parameter in Java:

public class SimpleTesting  public static void main(String[] args)   ArrayListInteger> evens = new ArrayListInteger>();  evens.add(10);  evens.add(20);  evens.add(30);  evens.add(40);  evens.forEach( (n) ->  System.out.println(n); > ); // passing lambda as a parameter  > > 

Pass a Method as a Parameter to a Custom Method in Java

Apart from the built-in method forEach() , we can pass it as a parameter to a custom method. In this example, we created an interface Doable having a method doSomething() . In the SimpleTesting class, we have a method show() that calls the doSomething() method. Inside the main() method, we created a lambda function and passed it to the show() method.

Notice that this is the line where we are passing a method (lambda function) as a parameter to a method.

show("Hello", doa); // passing lambda function as parameter 
interface Doable  String doSomething(String str); > public class SimpleTesting  public static void main(String[] args)   Doable doa = (str)-> str+" Rohan";  show("Hello", doa); // passing lambda function as parameter  >   public static void show(String msg, Doable doa)   String greeting = doa.doSomething(msg);  System.out.println(greeting);  > > 

Pass a Method as a Parameter Using the Method Reference in Java

This is another solution that can be used to pass a method as a parameter to a method. It was also introduced with the lambda function in Java 8 version. In this example, we used the method reference concept to pass the show() method as a parameter to the Thread() constructor, which executes during runtime. See the output of the code example here:

public class SimpleTesting  public static void main(String[] args)   // Passing method reference as a parameter  Thread thread = new Thread(SimpleTesting::show);  thread.start();  >  public static void show()   System.out.println("My Thread");  > > 

Источник

Pass Method as a Parameter in Java 8

Pass a Method as a Parameter or Argument in Java 8 - Techndeck

In this tutorial, you are going to learn ‘how to pass method as a parameter in Java’ . and to do that, we are going to use unique concepts introduced in Java 8 and sample codes are provided below to help you understand better.

Before Java 8, there were no such thing as passing method as an argument but Java 8 introduced Lambda Expressions and Method References which can be used to pass as an argument. All thanks to the concept of OOPS and its support of functional style of writing code.

Pass Method as a Parameter using Lambda Function

In this example, we are iterating an ArrayList and then printing each value of the list. It’s a very simple example where we are passing the Lambda function to the forEach() method. This lambda function is just taking the argument and printing it using sysout.

List listOfStudents = Arrays . asList ( «Sam» , «Henry» , «Yash» , «Yashika» , «Donna» , «Victoria» , «John» , «Jenny» ) ;

listOfStudents . forEach ( x — > System . out . println ( x ) ) ; //Passing Lambda Function as an argument to another function >

Output:

Pass Method as a Parameter using Consumer Interface

In this example, we are iterating an Array List and printing the values which starts with character ‘J’. Java 8 introduced Functional interfaces and in that, one is Consumer Interface. CI takes one input argument and return no result. and the interesting thing is that Lambda expressions can be stored in variable as long as the variable’s type is an interface which has only one method and this perfectly suits to Consumer Interface.

Therefore, in the below example, we are creating a lambda expression and then storing it into a Consumer interface variable and then supplying it to forEach() method. If you are thinking why we are using consumer interface is because the list’s forEach() method takes consumer interface as its parameter. Look at the below example:

Источник

Java Pass Method as Parameter

To pass a method as a parameter in Java, you can use a functional interface and a lambda expression.

A functional interface is an interface that has a single abstract method. In Java, functional interfaces are usually annotated with the @FunctionalInterface annotation. For example:

@FunctionalInterface public interface MyFunction < void apply(); >

To pass a method as a parameter, you can create a lambda expression that implements the abstract method of the functional interface. For example:

MyFunction f = () -> System.out.println("Hello, World!");

You can then pass the lambda expression as a parameter to a method:

public void execute(MyFunction f) 

To call the execute() method and pass the lambda expression as a parameter, you can do the following:

Alternatively, you can pass the lambda expression directly as a parameter:

execute(() -> System.out.println("Hello, World!"));

I hope this helps! Let me know if you have any questions.

BookDuck

  • Is Java «pass-by-reference» or «pass-by-value»?
  • How do I read / convert an InputStream into a String in Java?
  • Avoiding NullPointerException in Java
  • What are the differences between a HashMap and a Hashtable in Java?
  • How do I generate random integers within a specific range in Java?
  • How do I efficiently iterate over each entry in a Java Map?
  • How can I create a memory leak in Java?
  • When to use LinkedList over ArrayList in Java?
  • How do I convert a String to an int in Java?
  • Does Java support default parameter values?
  • How to pass a function as a parameter in Java?

Источник

Java Program to pass method call as arguments to another method

In this article, we will understand how to pass method call as arguments to another method. We can call a method from another class by just creating an object of that class inside another class. After creating an object, call methods using the object reference variable.

Below is a demonstration of the same −

Enter two numbers : 2 and 3

The desired output would be −

The cube of the sum of two numbers is: 125

Algorithm

Step 1 - START Step 2 - Declare two variables values namely my_input_1 and my_input_2 Step 3 - We define a function that takes two numbers, and returns their sum. Step 4 - We define another function that takes one argument and multiplies it thrice, and returns the output. Step 5 - In the main function, we create a new object of the class, and create a Scanner object. Step 6 - Now, we can either pre-define the number or prompt the user to enter it. Step 7 - Once we have the inputs in place, we invoke the function that returns the cube of the input. Step 8 - This result is displayed on the console.

Example 1

Here, the input is being entered by the user based on a prompt. You can try this example live in ourcoding ground tool .

import java.util.Scanner; public class Main < public int my_sum(int a, int b) < int sum = a + b; return sum; >public void my_cube(int my_input) < int my_result = my_input * my_input * my_input; System.out.println(my_result); >public static void main(String[] args) < Main obj = new Main(); int my_input_1, my_input_2; System.out.println("Required packages have been imported"); Scanner my_scanner = new Scanner(System.in); System.out.println("A reader object has been defined "); System.out.print("Enter the first number : "); my_input_1 = my_scanner.nextInt(); System.out.print("Enter the second number : "); my_input_2 = my_scanner.nextInt(); System.out.println("The cube of the sum of two numbers is: "); obj.my_cube(obj.my_sum(my_input_1, my_input_2)); >>

Output

Required packages have been imported A reader object has been defined Enter the first number : 2 Enter the second number : 3 The cube of the sum of two numbers is: 125

Example 2

Here, the integer has been previously defined, and its value is accessed and displayed on the console.

public class Main < public int my_sum(int a, int b) < int sum = a + b; return sum; >public void my_cube(int my_input) < int my_result = my_input * my_input * my_input; System.out.println(my_result); >public static void main(String[] args) < Main obj = new Main(); int my_input_1, my_input_2; my_input_1 = 3; my_input_2 = 2; System.out.println("The two number is defined as " +my_input_1 +" and " +my_input_2); System.out.println("The cube of the sum of two numbers is: "); obj.my_cube(obj.my_sum(my_input_1, my_input_2)); >>

Output

The two number is defined as 3 and 2 The cube of the sum of two numbers is: 125

Источник

Оцените статью