1) Java 8 SAM

https://stackoverflow.com/questions/23342499/why-functional-interfaces-in-java-8-have-one-abstract-method

2) Use-of-functional-interface-in-java-8

https://stackoverflow.com/questions/36881826/what-is-use-of-functional-interface-in-java-8

3) Functional-interface-vs-abstract-class

https://stackoverflow.com/questions/19950013/java-8-functional-interface-vs-abstract-class

4) Functional-interface-with-no-arguments-and-no-return-value

https://stackoverflow.com/questions/23868733/java-8-functional-interface-with-no-arguments-and-no-return-value

5) Valid Functional Interface definitions

  • This can be used in lambda expression:
public interface Foo {
  public void doSomething();
}
  • This cannot be used in lambda expression:
public interface Foo {
  public void doSomething();
  public void doSomethingElse();
}
  • This will give compilation error:
@FunctionalInterface
public interface Foo {
  public void doSomething();
  public void doSomethingElse();
}

Invalid ‘@FunctionalInterface’ annotation; Foo is not a functional interface

 

6) Use Bifunction to add two values & print it.

package com.codinko.function;
import java.util.function.BiFunction;
public class BiFunctionDemo {
    public static void main(String[] args) {
        BiFunction<Integer, Integer, String> biFunction = 
                      (num1, num2) -> "Result:" +(num1 + num2);
        System.out.println(biFunction.apply(20,25));
    }    
}
  • Another use-case of BiFunction.
Map<String,BiFunction<Integer,Integer,Integer>> operators = 
                       new HashMap<>();
operators.put("+", (a,b) -> a + b);
operators.put("-", (a,b) -> a - b);
operators.put("*", (a,b) -> a * b);

 

7) Difference between BiFunction and BiConsumer?

  • BiFunction accepts two arguments and returns a value.
  • BiConsumer accepts two arguments but does not return value

8) BiConsumer/BiFunction/BiPredicate ?

https://www.concretepage.com/java/jdk-8/java-8-biconsumer-bifunction-bipredicate-example

  • java.util.function.BiPredicate is a functional interface which accepts two argument and returns Boolean value

9) How do you implement an interface that has a run() and throws Exception?

Implement your own!

10) Iterate over values in Hashmap using lambdas , use Consumer or BiConsumer as you feel the need.

import java.util.HashMap;
import java.util.Map;
import java.util.function.BiConsumer;
public class BiConsumerDemo {
   public static void main(String[] args) {
       Map<Integer,String> map = new HashMap<>();
       map.put(1, "A");
       map.put(2, "B");
       map.put(3, "C");
       BiConsumer<Integer,String> biConsumer = (key,value) -> 
		System.out.println("Key:"+ key+" Value:"+ value);
       map.forEach(biConsumer);
   }    
}
Output will be as below.
Key:1 Value:A
Key:2 Value:B
Key:3 Value:C