How to specify function types for void (not Void) methods in Java8?

I’m playing around with Java 8 to find out how functions as first class citizens. I have the following snippet:

package test;

import java.util.*;
import java.util.function.*;

public class Test {

    public static void myForEach(List<Integer> list, Function<Integer, Void> myFunction) {

    public static void displayInt(Integer i) {

    public static void main(String[] args) {
      List<Integer> theList = new ArrayList<>();
      myForEach(theList, Test::displayInt);

What I’m trying to do is pass method displayInt to method myForEach using a method reference. To compiler produces the following error:

src/test/ error: cannot find symbol
  symbol:   method functionToBlock(Function<Integer,Void>)
  location: class Test
src/test/ error: method myForEach in class Test cannot be applied to given ty
      myForEach(theList, Test::displayInt);
  required: List<Integer>,Function<Integer,Void>
  found: List<Integer>,Test::displayInt
  reason: argument mismatch; bad return type in method reference
      void cannot be converted to Void

The compiler complains that void cannot be converted to Void. I don’t know how to specify the type of the function interface in the signature of myForEach such that the code compiles. I know I could simply change the return type of displayInt to Void and then return null. However, there may be situations where it’s not possible to alter the method I want to pass somewhere else. Is there an easy way to reuse displayInt as it is?

Best Answer

Leave a Comment