Friday, March 25, 2022

Lambda expressions in Java

Lambda expressions are used to provide the implementation of a functional interface. As shown below it saves a lot of code.

@FunctionalInterface
interface Shape {
    void draw();
}

public class Main {
    public static void main(String[] args) {
        //implementing Shape using anonymous class
        Shape shape1 = new Shape() {
            @Override
            public void draw() {
                System.out.println("Drawing a shape without lambda");
            }
        };
        shape1.draw();

        //implementing Shape with lambda
        Shape shape2 = () -> System.out.println("Drawing a shape with lambda");
        shape2.draw();
    }
}

Lambda expressions can be stored in variables if the variable's type is an interface which has only one method. As shown below we have stored the filter condition in a variable.

List<String> list = new ArrayList<>();
list.add("apple");
list.add("ball");
list.add("cat");
list.add("aeroplane");
Predicate<String> startsWithLetterA = s -> s.startsWith("a");
list.stream().filter(startsWithLetterA).forEach(System.out::println);

Choose valid lambda expression for the following code

List<String> list = new ArrayList<>();
list.removeIf(______________________);
  • [x] s -> s.isEmpty() //valid
  • [ ] s -> {s.isEmpty()} //invalid since return keyword is missing
  • [ ] s -> {s.isEmpty();} //invalid since return keyword is missing
  • [x] s -> {return s.isEmpty();} //valid
  • [ ] s -> {return s.isEmpty()} //invalid since semicolon expected
  • [ ] String s -> s.isEmpty() //invalid since missing parantheses around String s
  • [x] ( String s ) -> s.isEmpty() //valid
  • [ ] s -> {String s = ""; return s.isEmpty();} // invalid since variable s is already in use and cannot be redefined

No comments:

Post a Comment