Java 8 Lambda expression with Serialization
You can create a serializable lambda expression via
Collections.sort(people, (Comparator<Person>&Serializable)
(p1, p2) -> p1.getLastName().compareTo(p2.getLastName()));
but it should be noted, that creating a Comparator
via
(p1, p2) -> p1.getLastName().compareTo(p2.getLastName())
bears a discouraged redundancy. You are calling getLastName()
twice and have to care to invoke it on the right parameter variable in either case. It is more straight-forward to use
Comparator.comparing(Person::getLastName)
instead. You can also make this comparator serializable, though that implies loosing much of the conciseness:
Collections.sort(people,
Comparator.comparing((Function<Person,String>&Serializable)Person::getLastName));
This is also more robust. The serialized form of a lambda expression contains a reference to the implementation method, which is in the first variant a synthetic method with a compiler generated name that might change when you use another lambda expression within the defining method. In contrast, Person::getLastName
points the the named method getLastName
as implementation method (at least with javac
).
But generally, serializable lambda expressions might contain surprising compiler dependencies and should be used with care.
Since they are meant to describe behavior rather than data, there is no point in long-term storage of them anyway. For transferring them between JVMs with the same code base, they are sufficient.