Search code examples
java-8functional-interface

The target type of this expression must be a functional interface -Java 8 Functoinal Interface


I just have a small doubt on lambdas.I'm getting the below error with the following code.If i'm calling a method which returns boolean or other type, I don't see this issue.How can i solve this problem?

Error:

Exception in thread "main" java.lang.Error: Unresolved compilation problems: The method forEach(Consumer) in the type Iterable is not applicable for the arguments (( bean) -> {}) The target type of this expression must be a functional interface

at com.wipro.MethodReference.main(MethodReference.java:18)

package com.sample;

import com.student.MockClass;

import java.util.ArrayList;
import java.util.List;

public class MethodReference {
    public static void main(String[] args) {
        MockClass obj = new MockClass("JSP", 2);
        MockClass obj1 = new MockClass("Java", 8);
        List<MockClass> listofBeans = new ArrayList<MockClass>();
        listofBeans.add(obj);
        listofBeans.add(obj1);
        listofBeans.forEach(bean -> MethodReference::call);
    }

     public static void call(){
        System.out.println("Hii!!!");
    }    
}

Solution

  • The purpose of functional interfaces (in this case a Consumer) is to pass data through the stream. Your method call() makes not much sense since it accepts no parameter and returns nothing. You can do it but not with a method reference.

    Try this instead:

    listofBeans.forEach(MethodReference::call);
    public static void call(MockClass bean){...}
    

    or

    listofBeans.forEach(bean -> call());