简体   繁体   中英

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

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 ?

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.

It's :

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

or even simpler :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM