43

I saw a code in java 8 to iterate a collection.

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
numbers.forEach(System.out::println);

What is the functionality of System.out::println ? And how the above code can iterate through the List.

And what is the use of the operator :: , Where else we can use this operator ?

prime
  • 14,464
  • 14
  • 99
  • 131

1 Answers1

92

It's called a "method reference" and it's a syntactic sugar for expressions like this:

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

Here, you don't actually need the name x in order to invoke println for each of the elements. That's where the method reference is helpful - the :: operator denotes you will be invoking the println method with a parameter, which name you don't specify explicitly:

numbers.forEach(System.out::println);
Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147