Favor Lambdas Over Anonymous Classes

 class​ Calculator {
 
  Map<Double, Double> values = ​new​ HashMap<>();
 
  Double square(Double x) {
  Function<Double, Double> squareFunction =
»new​ Function<Double, Double>() {
  @Override
 public​ Double apply(Double value) {
 return​ value * value;
  }
  };
 return​ values.computeIfAbsent(x, squareFunction);
  }
 }

In Java 8, several existing classes (such as Map) got a boost with more useful methods. In the code above, you can see one of them named computeIfAbsent(). This method gets a value from the map using its key, and if the key isn’t already present in the map, it computes the value first. Pretty neat. We’ve written similar code many times by hand before.

But to use that new method, ...

Get Java By Comparison now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.