
Now instead of using the lambda expression that invokes the one-argument constructor directly, I can use a constructor reference instead. map(name -> new Person(name)) // lambda expression Given a list of string names, I can map them to Person instances using the one-argument constructor.Īrrays.asList("Grace Hopper", "Barbara Liskov", "Ada Lovelace", … equals, hashCode, toString methods … All it does is wrap a simple string attribute called name.

That’s a constructor reference, which I would like to illustrate here.įirst, here is the Person class, which is just about the simplest Plain Old Java Object (POJO) imaginable. What if you want to go the other way? What if you have a list of strings and you want to create a list of Person references from it? In that case you can use a method reference again, but this time using the keyword new. Lambda expressions can be far more complicated and versatile. The method reference is slightly shorter, and makes clear that the only thing being done to each person is transforming it using the getName method. map(Person::getName) // method reference That works, but most developers would use a method reference instead: In other words, take a list of Person instances, turn it into a stream, map each one to a String by invoking the getName() method on it, and collect them back into a List. map(person -> person.getName()) // lambda expression For example, say you had a list of people and you wanted to convert it to a list of names.

When people talk about the new syntax added to Java 8, they mention lambda expressions, method references, and streams.

Use the new keyword as part of a method reference. You want to instantiate an object using a method reference as part of a stream pipeline.
