Hi there,
What are these "::" symbols being used for?
I found them in
universityGroup.students.forEach(System.out::println);
where sturdents comes from
public class UniversityGroup {
public List<String> students;
thanks
Use of ::
Under discussion
Comments (3)
- Popular
- New
- Old
You must be signed in to leave a comment
LuisRC
19 January 2022, 11:18
Thanks Lisa. I think I should read your answer more than once because of my current Java level.
0
Lisa
19 January 2022, 11:48
Better would be to forget my answer for now. Move on, learn core Java now and when you have the knowledge necessary you can dive into that topic. It's cool (at least I think so 😜🤪) but if it is not possible to understand what's going on, then it makes no sense at all to wast time with that.
0
Lisa
19 January 2022, 10:25
That's the method reference operator. At this time this is hard to explain but it is used for functional programming. You do not pass a value, a state to a method but a function. Means the behavior of the method you invoke is dependent on the function you pass it.
To understand that fully you'd need to know what System.out is (~lvl 18-20), a static PrintStream variable and you need to know what an anonymous inner class is (somewhere in the middle of the multithreading quest).
Then, with some inner class practice, you can explore on your own lambdas. When you mastered these you can do the next step to method references.
I try it in short, forEach is a method of the Collection via the Iterable interface so you have it available for every collection like ArrayList or HashSet. It executes the passed action on every element of the collection. You need to pass anything that implements the Consumer interface (if you use classes, anon inner classes). But this is different for method references. You can pass that forEach method that way not only a Consumer but also any method that has the same definition as the functional method declared in consumer (returning nothing but taking one element). The println method of the System.out stream does exactly that. It takes an argument and has no return value. In the end all elements of the collection get output on the console in a new line. Similar to an ordinary loop and calling println on each element.
Here you see that you can use any method as argument for forEach that has the same definition as the Consumer accept method. Here even an instance method I wrote. 0