27

I stumbled upon the following Java code which is using a method reference for System.out.println:

class SomeClass {
    public static void main(String[] args) {
           List<Integer> numbers = Arrays.asList(1,2,3,4,5,6,7,8,9);
           numbers.forEach(System.out::println);
        }
    }
}

What is the equivalent lambda expression for System.out::println?

3
  • 4
    It is not exactly functional though :-)
    – Stephen C
    Jan 19, 2015 at 11:35
  • @StephenC can u plz suggest why?
    – Aakash
    Jan 19, 2015 at 11:36
  • 6
    Well println is hardly a side-effect free function ... is it.
    – Stephen C
    Jan 19, 2015 at 13:40

2 Answers 2

61
+200

The method reference System.out::println will evaluate System.out first, then create the equivalent of a lambda expression which captures the evaluated value. Usually, you would use
o -> System.out.println(o) to achieve the same as the method reference, but this lambda expression will evaluate System.out each time the method will be called.

So an exact equivalent would be:

PrintStream p = Objects.requireNonNull(System.out);
numbers.forEach(o -> p.println(o));

which will make a difference if someone invokes System.setOut(…); in-between.

3
  • I do understand that invocation target of a method reference is evaluated when its declaration is first encountered, that is logical to me. But is there a jls part that explicitly says this(I've really tried to find it... ). If invocation target is a method, one could capture the method and this for example, not the actual object that the method returns... as far as I understand. Or did I get that entirely wrong?
    – Eugene
    Jun 15, 2017 at 13:32
  • never mind... First, if the method reference expression begins with an ExpressionName or a Primary, this subexpression is evaluated
    – Eugene
    Jun 15, 2017 at 13:34
  • This comes under bound type method reference and the same is explained in youtube.com/watch?v=7qXfoZIqi2Q at time line 17:20.
    – sankar
    Jan 7 at 3:57
6

It's :

numbers.forEach(i -> {System.out.println(i);});

or even simpler :

numbers.forEach(i -> System.out.println(i));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.