47

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 ?

0

1 Answer 1

100

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);
Sign up to request clarification or add additional context in comments.

9 Comments

so what are other use of the :: operator ?
It's used only for method references.
commenting quite late but what is the REAL advantage ? is this not making the code less readable and less maintainable ?
@Holger absolutely . To add more to that, one can refer Joshua Bloch speech youtube.com/watch?v=7qXfoZIqi2Q at timeline 17:20. This comes under bound type method reference.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.