Java Lambda Expressions

http://(https://hackernoon.com/tensorflow-is-dead-long-live-tensorflow-49d3e975cf04This morning I read the post on Medium named “TensorFlow is dead, long live TensorFlow!” by Cassie Kozyrkov who is a Chief Decision Intelligence Engineer at Google. After lunch will spend some time watching the videos embedded in the post and over the weekend will see if I can take TensorFlow 2.o on a Linux machine for a spin. I have a version of TensorFlow 1.0 installed on a Windows machine. Followed some tutorials but as Cassie puts  it so expressively, it was complicated to say the least.

After reading the post on Medium I selected on HackerRank the Java Lambda Expressions challenge. Half of it was dealing with lambda expressions and the other half was generating the code to check for prime numbers.

The requirements are to write three lambda expressions to check for odd numbers, check for palindromes and check for prime numbers. HackerRank provides the testing scaffolding as the main() method in the Solution class. You only have to fill in the code. Please note that the code provided is missing the closing bracket ‘}’ for the MyMath class. Not sure what the purpose of that was.

The following shows the edited contents of the console in my Eclipse IDE which I used to develop my solution:

5
1 4
2 5
3 898
1 3
2 12
EVEN
PRIME
PALINDROME
ODD
COMPOSITE


3
2 0
2 1
2 2
COMPOSITE
COMPOSITE
PRIME


1
2 9
COMPOSITE


13
2 1
2 2
2 3
2 4
2 5
2 6
2 7
2 8
2 9
2 10
2 11
2 12
2 13
COMPOSITE
PRIME
PRIME
COMPOSITE
PRIME
COMPOSITE
PRIME
COMPOSITE
COMPOSITE
COMPOSITE
PRIME
COMPOSITE
PRIME

Before attempting to address the solution, I did read the Lambda Expression tutorial by Oracle. Given there is time available, I always like to read about the subject at hand before diving into coding. Seems that in most cases there are new things to learn or at least review concepts and techniques.

Lambda expressions allow you express instances of single-method classes more compactly.

interface PerformOperation {
	boolean check(int a);
}

This is a very simple interface. It is a functional interface because it contains only one abstract method. This method takes one parameter and returns a Boolean value. The method is so simple that it might not be worth it to define one in your application. The JDK defines several standard functional interfaces, which you can find in the package java.util.function.

Remember, to use a lambda expression, you need to implement a functional interface.

Note that a lambda expression looks a lot like a method declaration; you can consider lambda expressions as anonymous methods—methods without a name.

/*
 * 
 */
class MyMath {
	
	// **** ****
	public static boolean checker(PerformOperation p, int num) {
		return p.check(num);
	}

	// **** check if a number is odd ****
	public PerformOperation isOdd() {
		
		// ???? ????
		return (num) -> {
			if (num % 2 != 0)
				return true;
			else
				return false;
		};
		
		// **** ****
//		return (num) -> num % 2 != 0;
	}
	
	// **** check is number is a palindrome ****
	public PerformOperation isPalindrome() {
		
		// ???? ????
		return (num) -> {
			String s = String.valueOf(num);
			String r = (new StringBuffer(s).reverse()).toString();
			return s.equals(r);
		};
		
		// **** ****
//		return (num) -> (String.valueOf(num).equalsIgnoreCase(new StringBuffer(String.valueOf(num)).reverse().toString()));
	}
	
	// **** ****
	public PerformOperation isPrime() {
		
//		// ???? ????
//		return (num) -> {
//			boolean flag = true;
//			
//			if (num <= 1)
//				flag = false;
//			else {
//				int sr = (int)Math.sqrt(num);
//				
//				for (int i = 2; i <= sr && flag; i++) {
//					
//					for (int j = i * i; j <= num; j += i) { // if (j == num) { // flag = false; // break; // } // } // // } // // } // // return flag; // };

        // **** ****
        return (num) -> num > 1 && java.util.stream.IntStream.range(2, num - 1).noneMatch(index->num % index == 0);
	}
}

In the last code snippet we implement each of the three required methods twice. They both work and seem to pass the tests. The code following the “// ???? ????” string denotes an implementation. A similar and simpler implementation is preceded by the “// **** ****” string.

The isPrime() method implements a modified version of the Sieve of Eratosthenes. I touched on that topic on a previous post.

The second implementation of isPrime() makes use of the IntStream class. We touched on the IntStream class in the Climbing the Leader board post earlier this month.

If interested, you can find my entire solution in my GitHub repository.

Hope you enjoyed and learned something new. If you have comments or questions regarding this post, or if you need help with a software development project at any stage in the SDLC, feel free to leave me a note bellow. Requests for help will not be made public.

Keep on reading and experimenting; it is the best way to learn.

John

Follow m eon Twitter:  @john_canessa.com

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.