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 Comparator through
(p1, p2) -> p1.getLastName().compareTo(p2.getLastName())
carries discouraged redundancy. You call getLastName() twice, and you will need to call it in the right parameter variable anyway. More straightforward to use
Comparator.comparing(Person::getLastName)
instead of this. You can also make this comparator serializable, although this implies losing most of the brevity:
Collections.sort(people, Comparator.comparing((Function<Person,String>&Serializable)Person::getLastName));
It is also more stable. The serialized form of the lambda expression contains a reference to the implementation method, which in the first embodiment is a synthetic method with a name generated by the compiler, which can change when using another lambda expression in the definition method. In contrast, Person::getLastName points to the named getLastName method as an implementation method (at least with javac ).
But as a rule, serializable lambda expressions can contain amazing compiler dependencies and should be used with caution.
Since they are intended to describe behavior, not data, in any case, their long-term storage does not make sense. To transfer them between JVMs with the same code base, they are sufficient.