Java Lambda Expressions: Math Example

|

Code Explanation

  1. Instance of MyMath: Creates an instance of MyMath called math.
  2. Tests for isOdd: Uses MyMath.checker with the isOdd operation to check if num1 and num2 are odd.
  3. Tests for isPrime: Uses MyMath.checker with the isPrime operation to check if num1 and num2 are prime.
  4. Tests for isPalindrome: Uses MyMath.checker with the isPalindrome operation to check if num3 and num1 are palindromic numbers.

Each of these test cases should print true or false based on the conditions of the number.

package tests;

import java.io.*;
import java.util.*;

interface PerformOperation {
	boolean check(int a);
}

class MyMath {
	public static boolean checker(PerformOperation p, int num) {
		return p.check(num);
	}
	public PerformOperation isOdd() {
		return (int num) -> num % 2 != 0;
	}

	public PerformOperation isPrime() {
		return (int num) -> {
			for(int i = 2; i * i <= num; i++) {
				if(num % i == 0) {
					return false;
				}
			}
			return true;
		};
	}

	public PerformOperation isPalindrome() {
		return (int num) -> {
			String original = Integer.toString(num);
			String reversed = new StringBuilder(original).reverse().toString();
			return original.equals(reversed);
		};
	}
}

public class Solution {
	
    public static void main(String[] args) {
        MyMath math = new MyMath();
        
        int num1 = 7;
        int num2 = 10;
        int num3 = 121;
        
        // Testing if the number is odd
        System.out.println(num1 + " is odd? " + MyMath.checker(math.isOdd(), num1)); // true
        System.out.println(num2 + " is odd? " + MyMath.checker(math.isOdd(), num2)); // false
        
        // Testing if the number is prime
        System.out.println(num1 + " is prime? " + MyMath.checker(math.isPrime(), num1)); // true
        System.out.println(num2 + " is prime? " + MyMath.checker(math.isPrime(), num2)); // false
        
        // Testing if the number is palindrome
        System.out.println(num3 + " is palindrome? " + MyMath.checker(math.isPalindrome(), num3)); // true
        System.out.println(num1 + " is palindrome? " + MyMath.checker(math.isPalindrome(), num1)); // false
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *