top of page

Lambda Expressions 

arrow.png
arrow_edited_edited.jpg

 Lambda expressions were introduced in Java 8 as a way to provide a concise syntax for writing anonymous functions (implementations of functional interfaces). Lambda expressions are particularly useful when working with functional interfaces, which have a single abstract method (SAM).
 

Basic syntax of a lambda expression 1:             (parameters) -> expression

                     // Functional interface
               interface Greeting {
                    // A single abstract method
                void greet(String name);
                  }


public class LambdaExpressionExample {


       public static void main(String[] args) {
                  // Using a lambda expression to implement the Greeting interface       

        Greeting greetFunction = (name)-> System.out.println("Hello," + name + "!");      
                // Calling the greet method using the lambda expression

         greetFunction.greet("John");
         greetFunction.greet("Alice");
      }
}


In this example: 

               Greeting is a functional interface with a single abstract method greet.
               The lambda expression (name)-> System.out.println("Hello," + name + "!");  implements the greet method of the Greeting interface.  The lambda expression takes a single parameter name and prints a greeting message to the
console.  
When the greet method is called with different names, the lambda expression is executed, and the appropriate greeting is printed.


Basic syntax of a lambda expression 2:                            (parameters) -> { statements; }
                / Functional interface with a single abstract method
                      interface MathOperation {
                          int operate(int a, int b);
                          }
   public class LambdaExpressionExample {
   public static void main(String[] args) {
                // Using a lambda expression to implement the MathOperation interface
    MathOperation addition = (a, b) -> {
                                    int result = a + b;
                                   System.out.println("Adding" + a + " and " + b + ":" + result);
                                   return result;
                                };

    MathOperation subtraction = (a, b) ->{
                                    int result = a - b;
                                    System.out.println("Subtracting " + b + " from " + a +": "+ result);
                                    return result;
                                 
};
           // Performing operations using lambda expressions
           int resultAddition = addition.operate(10, 5);
           int resultSubtraction = subtraction.operate(10, 5);
           System.out.println("Result of Addition: " + resultAddition);
           System.out.println("Result of Subtraction: " + resultSubtraction);

      }
}

In this example: 

                  MathOperation is a functional interface with a single abstract method operate. Two lambda expressions are used to implement the operate method with the { statements; } syntax.
                The lambda expressions perform addition and subtraction operations and print the results with additional statements. When the operate method is called with specific values, the lambda expressions are executed, and the corresponding statements are executed.

                     The expected output:
                                  Adding 10 and 5: 15
                                  Subtracting 5 from 10: 5
                                  Result of Addition: 15
                                  Result of Subtraction: 5

                    Example 4: Lambda Expression with forEach                

                                  import java.util.Arrays;
                                  import java.util.List;
                                  public class LambdaForEachExample {
                                  public static void main (String[] args) {
                                             List<String> fruits =Arrays.asList("Apple","Banana", "Orange", "Grapes");
                                                      // Using lambda expression with forEach to iterate through the list
                                              fruits.forEach(fruit ->System.out.println("I love " + fruit));
                                                     // Another example using method reference
                                               fruits.forEach(System.out::println);
                                      }
                                    }
In this example:

           The fruits list contains a collection of strings.
           The forEach method is used with a lambda expression to iterate through each element of the list
and perform an action.  The lambda expression (fruit -> System.out.println("I love " + fruit)) takes each element (fruit) and prints a corresponding message.

The output of the program will be:
            I love Apple
            I love Banana
            I love Orange
            I love Grapes
            Apple
            Banana
            Orange

            Grapes
            Alternatively, we can use a method reference (System.out::println) instead of a lambda expression when the action is to call a method with the same signature as the Consumer functional interface.

Lambda Expressions to find sum of squares, cubes, and odd numbers for a fixed list of integers
        import java.util.Arrays;
        import java.util.List;
         public class FindSquareAndSum {
         public static void main(String[] args) {
                         // Calculate and print the sum of squares
                         int resultSquare = findSquareAndSums();
                         System.out.println("Sum of Squares: " + resultSquare);
                          // Calculate and print the sum of cubes
                          int resultCube = findCubeAndSums();
                          System.out.println("Sum of Cubes: " + resultCube);
                          // Calculate and print the sum of odd numbers
                          int resultOdd = findOddAndSums();
                          System.out.println("Sum of Odd Numbers: " + resultOdd);
                      }
      // Calculate the sum of squares for the fixed list of numbers
         private static Integer findSquareAndSums() {
                   List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
     // Use Java Streams to map each number to its square and then reduce to find the sum
                    return numbers.stream().map(n -> n * n).reduce(0, (x, y) -> x + y);
            }
      // Calculate the sum of cubes for the fixed list of numbers
         private static Integer findCubeAndSums() {
                   List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
     // Use Java Streams to map each number to its cube and then reduce to find the sum
                 return numbers.stream().map(n -> n * n * n).reduce(0, (x, y) -> x + y);
           }
        // Calculate the sum of odd numbers for the fixed list of numbers
        private static Integer findOddAndSums() {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
        // Use Java Streams to filter odd numbers and then reduce to find the sum
        return numbers.stream().filter(n -> n % 2 == 1).reduce(0, (x, y) -> x + y);

      }
      }
Explanation:
          The findSquareAndSums, findCubeAndSums, and findOddAndSums methods use Java Streams
to perform the desired operations on the list of numbers.
           map is used to transform each element of the stream (number) according to the specified
operation (square, cube, or filter odd numbers).

           reduce is then used to perform the summation operation ((x, y) -> x + y) on the stream
elements, starting with an initial value of 0.

The main method calls these methods and prints the results for the sum of squares, cubes, and
odd numbers.


       When we run this program, it should output the sums as follows:
          Sum of Squares: 385
          Sum of Cubes: 3025
          Sum of Odd Numbers: 25


  Lamda Expression And Filters
      import java.util.ArrayList;
      import java.util.Arrays;
      import java.util.List;
      public class LamdaExpressionAndFilters {
      public static void main(String[] args) {
              // Creating a list of cities
              List<String>cities = new ArrayList<>(Arrays.asList("Paris", "New York", "London"));
              // Using forEach with method reference to print each city
             cities.stream().forEach(System.out::println);
              // Using forEach with lambda expression to achieve the same result
             cities.stream().forEach(n -> System.out.println(n));
              // Filtering and printing cities containing the letter &quot;k&quot;
              cities.stream().filter(n -> n.contains("k")).forEach(System.out::println);
              // Filtering and printing cities with length greater than 6
              cities.stream().filter(n -> n.length() > 6).forEach(n -> System.out.println(n));
              // Mapping and printing uppercase version of each city
              cities.stream().map(n -> n.toUpperCase()).forEach(n ->System.out.println(n));
              // Mapping and printing uppercase version using method reference
              cities.stream().map(String::toUpperCase).forEach(n -> System.out.println(n));

               // Mapping to concatenate city name with its length and printing
              cities.stream().map(n -> n + "-" + n.length()).forEach(System.out::println);
     }

​

Git Basic Commands

Slide2.JPG

Calculate the sum of a list of numbers using traditional and functional programming approaches in Java

The functional approaches leverage Java's Stream API for more concise and expressive code.

import java.util.Arrays;

import java.util.List;

 

public class ReducedMethod {

 

    public static void main(String[] args) {

        // Calculate and print the sum using the addNumbersFunctional1 method

              int sum1 = addNumbersFunctional1();

              System.out.println("Sum calculated using addNumbersFunctional1: " + sum1);

         // Calculate and print the sum using the addNumbersFunctional2 method

             int sum2 = addNumbersFunctional2();

            System.out.println("Sum calculated using addNumbersFunctional2: " + sum2);

   // Calculate and print the sum using the addNumbersFunctional3 method

           int sum3 = addNumbersFunctional3();

          System.out.println("Sum calculated using addNumbersFunctional3: " + sum3);

    }

            // Traditional method to add two numbers

                            private static int addNumbers(int a, int b) {

                                      return a + b;

                                  }

 

    // Calculate the sum using the functional approach with a method reference (addNumbers)

    public static Integer addNumbersFunctional1() {

        List<Integer> numbers = Arrays.asList(61, 24, 73, 49, 95, 26, 17, 88, 9, 34);

             return numbers.stream().reduce(0, ReducedMethod::addNumbers);

    }

 

    // Calculate the sum using the functional approach with a lambda expression

    public static Integer addNumbersFunctional2() {

        List<Integer> numbers = Arrays.asList(61, 24, 73, 49, 95, 26, 17, 88, 9, 34);

        return numbers.stream().reduce(0, (x, y) -> x + y);

    }

 

    // Calculate the sum using the functional approach with Integer.sum method reference

    public static Integer addNumbersFunctional3() {

        List<Integer> numbers = Arrays.asList(61, 24, 73, 49, 95, 26, 17, 88, 9, 34);

        return numbers.stream().reduce(0, Integer::sum);

    }

}

Explanation:

main Method:

The main method is the entry point of the program.

It calculates and prints the sum of numbers using three different approaches (addNumbersFunctional1, addNumbersFunctional2, and addNumbersFunctional3).

Traditional Method (addNumbers):

The addNumbers method is a traditional approach to add two numbers.  This method is used as a reference in the functional approach (addNumbersFunctional1).

Functional Approach (addNumbersFunctional1, addNumbersFunctional2, addNumbersFunctional3):

These methods use functional programming constructs introduced in Java 8 with the Stream API.

  • addNumbersFunctional1 uses a method reference to the addNumbers method.

  • addNumbersFunctional2 uses a lambda expression directly.

  • addNumbersFunctional3 uses the Integer::sum method reference, provided by the Integer class for adding two integers.

List of Numbers:

A list of integers (numbers) is created using Arrays.asList. This list is used to demonstrate the functional approaches.

Stream and Reduce Operation:

The stream() method is used to convert the list into a stream of elements.

The reduce operation is applied to accumulate the elements of the stream into a single result (in this case, the sum).

Printing the Results:

The results of the different approaches are calculated and printed to the console in the main method.

 Java Streams - Examples

import java.util.Arrays;

import java.util.OptionalDouble;

import java.util.stream.Stream;

 

public class StreamExamples {

 

    public static void main(String[] args) {

    // Count the number of elements in the stream

     System.out.println(Stream.of(76, 98, 45, 63, 23, 12).count());

     // Calculate the average of elements in an array

       int[] numArray = {76, 98, 45, 63, 23, 12};

      OptionalDoubleave = Arrays.stream(numArray).average();

      System.out.println(ave);

     // Count the number of elements in an array

        int howMany = (int) Arrays.stream(numArray).count();

System.out.println(howMany);

         // Find the maximum value in an array

System.out.println("Max : " + Arrays.stream(numArray).max());

         // Find the minimum value in an array

System.out.println("Min : " + Arrays.stream(numArray).min());

         // Calculate the sum of elements in an array

System.out.println("Sum : " + Arrays.stream(numArray).sum());

    }

}

 Explanation:

​

 Counting Elements in a Stream:

Stream.of(76, 98, 45, 63, 23, 12).count() counts the number of elements in the stream created using Stream.of.

The result is printed using System.out.println.

​

 Calculating Average of an Array:

                                   Arrays.stream(numArray).average(); creates a stream from the array numArray and calculates the average.

The result is an OptionalDouble since the array might be empty.  The average is printed using System.out.println(ave).

​

 Counting Elements in an Array:

                                 Arrays.stream(numArray).count(); counts the number of elements in the array numArray.

The result is cast to an int and printed using System.out.println(howMany).

​

 Finding Maximum and Minimum Values:

                                Arrays.stream(numArray).max(); finds the maximum value in the array. The result is an OptionalInt. Arrays.stream(numArray).min(); finds the minimum value in the array. The result is an OptionalInt.

Both results are printed using System.out.println.

​

 Calculating Sum of Elements:

                                Arrays.stream(numArray).sum(); calculates the sum of elements in the array numArray.

The result is printed using System.out.println.

bottom of page