How to serialize a lambda function in Java?

The Serialization is a process for writing the state of an object into a byte stream so that we can transfer it over the network. We can serialize a lambda expression if its target type and its captured arguments have serialized. However, like inner classes, the serialization of lambda expressions is strongly discouraged.

In the below example, we can serialize and deserialize a lambda function using a Function interface.


import java.util.function.Function;

interface MyInterface {
   void hello(String name);
class MyImpl implements MyInterface {
   public void hello(String name) {
      System.out.println("Hello " + name);

public class SerializeDeSerializeLambdaTest {
   public static void main(String[] args) throws Exception {
   private static void serializeAndDeserializeFunction() throws Exception {
      Function<String, String> fn = (Function<String, String> & Serializable) (n)
-> "Hello " + n; // serialize a lambda function
      System.out.println("Run original function: " + fn.apply("Raja"));

      String path = "./serialized-fn";
      serialize((Serializable) fn, path);
      System.out.println("Serialized function to " + path);

      Function<Strng, String> deserializedFn = (Function<String, String>) deserialize(path);
      System.out.println("Deserialized function from " + path);
      System.out.println("Run deserialized function: " + deserializedFn.apply("Raja"));
   private static void serialize(Serializable obj, String outputPath) throws IOException {
      File outputFile = new File(outputPath);
      if(!outputFile.exists()) {
      try(ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(outputFile))) {
   private static Object deserialize(String inputPath) throws IOException, ClassNotFoundException {
      File inputFile = new File(inputPath);
      try(ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(inputFile))) {
         return inputStream.readObject();


Run original function: Hello Raja
Serialized function to ./serialized-fn
Deserialized function from ./serialized-fn
Run deserialized function: Hello Raja