w3resource

Java Lambda expression - Sum of two integers

Java Lambda Program: Exercise-1 with Solution

Write a Java program to implement a lambda expression to find the sum of two integers.

Sample Solution:

Java Code:

// SumCalculator.java 

interface SumCalculator {
    int sum(int a, int b);
}

// Main.java
public class Main {
    public static void main(String[] args) {
        SumCalculator sumCalculator = (x, y) -> x + y;
        int result = sumCalculator.sum(7, 6);
        System.out.println("Sum 7,6): " + result);
	result = sumCalculator.sum(15, -35);
        System.out.println("Sum 15, -35): " + result);
    }
}

Sample Output:

Sum 7,6): 13
Sum 15, -35): -20 

Explanation:

In the above exercise, a functional interface named SumCalculator is defined. This interface has a single abstract method called sum that takes two integer parameters and returns an integer result. The lambda expression (x, y) -> x + y is used to implement this method. It takes two integers, x and y, and returns their sum.

In the main method, an instance of the SumCalculator interface is created using the lambda expression and assigned to the variable sumCalculator. For calculating the sum, the sumCalculator is invoked with pairs of integer arguments. System.out.println prints the results to the console from the result variable.

Flowchart:

Flowchart: Java  Exercises: Sum of two integers.
Flowchart: Java  Exercises: Sum of two integers.

Live Demo:

Java Code Editor:

Improve this sample solution and post your code through Disqus

Java Lambda Exercises Previous: Java Lambda expression Exercises Home.
Java Lambda Exercises Next: Check if string is empty.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.

Java: Tips of the Day

How do I remove repeated elements from ArrayList?

If you don't want duplicates in a Collection, you should consider why you're using a Collection that allows duplicates. The easiest way to remove repeated elements is to add the contents to a Set (which will not allow duplicates) and then add the Set back to the ArrayList:

Set<String> set = new HashSet<>(yourList);
yourList.clear();
yourList.addAll(set);

Of course, this destroys the ordering of the elements in the ArrayList.

Ref: https://bit.ly/3bYIjNC

 





We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook