0

I know that lambdas are instances of interfaces that have only 1 abstract method. But doesn't that mean, every time there is a lambda expression, it also mean there is actually a new keyword there?

Runnable r1 = new Runnable()
{
  @Override
  public void run()
  {
    System.out.println("Hello World!");
  }
};
// equals to
Runnable r2 = () -> System.out.println("Hello World!");
// lambda equals to a new keyword

I want to know if it is a better practice to store a lambda to a variable in order to prevent unnessary creation of an object and garbage collection. For example, if I have a method that will turn a List<Object> to a List<String>:

import java.util.List;
import java.util.stream.Collectors;

public class Helper
{
  public static List<String> objectListToStringList(List<Object> objects)
  {
    return objects.stream()
      .map(o -> o.toString())
      .collect(Collectors.toList());
  }
}

Is it better to store the o -> o.toString() lambda to a variable in order to avoid the creation of a Function object when everytime this method was called?

import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

public class Helper
{
  private static final Function<Object, String> mapToString = o -> o.toString();

  public static List<String> objectListToStringList(List<Object> objects)
  {
    return objects.stream()
      .map(mapToString)
      .collect(Collectors.toList());
  }
}
Alex Cai
  • 35
  • 4
  • This might also come in handy (especially the accepted answer): https://stackoverflow.com/questions/53892875/java-lambda-expressions-and-memory-allocation – Thomas May 10 '23 at 06:14

0 Answers0