Problems and Solutions on Java Lambda Expressions

Q1. Print one simple text using the Lambda Expression (One Argument is passed inside the argument list).

Ans:-

public class Practice61 {
	
	//Functional interface which has only one abstract method //in it
//The return type of this hello abstract method is void
//but this method takes one String Argument	
	public interface HelloType {
		
		void hello (String text);
	}
	
public static void main(String [] args) {
	
	//(argument_list) -> {body}
	//this is how lambda works
	
//Here the argument is passed in the 
// Lambda expression without mentioning any type
//as it takes from the interface method
//Here one argument of String type is passed inside the argument //list
	HelloType helloLambda = (text1) -> {System.out.println("Hello " + text1);};

	helloLambda.hello("Ram");
										}
}

//Output
//Hello Ram

Q2. Print one simple text using the Lambda Expression (No Argument is passed inside the argument list).

Ans:-

public class Practice61 {
	
	//Functional interface which has only one abstract method in it
	
	public interface HelloType {
		
		void hello ();
	}
	
public static void main(String [] args) {
	
	//(argument_list) -> {body}
	//this is how lambda works
	
	HelloType helloLambda = () -> {System.out.println("Hello Ram");};
	//or this can also be written as mentioned below
	//as there is only one expression so we can remove the bracket of the body
	HelloType helloLambda1 = () -> System.out.println("Hello Ram");

	helloLambda.hello();
	helloLambda1.hello();
										}
}

Q3: Example of multiline expression inside the Lambda Body :-

  1. write one functional interface with a method having string argument and return type is integer.
  2. write one lambda expression which check the string input and will print zero when the string input is zero and will print number 1 in the console when the string input provided is one, for other values it will print -1 in the console.

Ans:-

public class Practice61 {
	
	//Functional interface which has only one abstract method in it
	
	public interface HelloType {
		
		int hello (String text);
	}
	
public static void main(String [] args) {
	
	//(argument_list) -> {body}
	//this is how lambda works
	//Here bracket is used as multi line expression is present inside the lambda expression
	
	
	HelloType helloType = (text) -> { switch (text) {
		case "zero": return 0;
		case "one": return 1;
		default: 
			return -1; 
			} };
			
			System.out.println(helloType.hello("zero"));
			System.out.println(helloType.hello("one"));
			System.out.println(helloType.hello("xxx"));
}}

1 Reply to “Problems and Solutions on Java Lambda Expressions”

Comments are closed.