As I tested, the below code executes without any issues. But I could not understand the logic. Can someone please explain?
public static void main(String[] args) {
List<String> london = new ArrayList<>(Arrays.asList("Chinatown","Croydon","Eden Park"));
class City{
private String name;
City(String name){
this.name = name;
}
public void printCity(){
System.out.println(name);
}
}
london.stream().map(City::new).forEach(City::printCity); //Chinatown,Croydon,Eden Park
}
In the above example code, I have following questions.
The consumer is equivalent to something like c -> c.printCity()
, (City c) -> c.printCity()
, or some long anonymous class that is a massive pain to type out.
The city instances are the subject of invocation. There is just syntactical sugar in the form of City::printCity
which passes the method to the expression, where the instance is called.