Monthly Archives: May 2015

Lambda: the new generation!


Java 8 brings lambdas. If you missed it here few samples:

// a method taking an interface with a single method
public void doRun(Runnable run) {
  // ....do something with run
}

// somewhere in code
doRun(() -> {
    // some java code
});
// or
doRun(this::methodWithNoParameter);

Of course you can also use parameters while they match. In 1 sentence we could say lambda are functions you can handle in java directly like class instances.

The most known use case for lambda is the new Java 8 stream integration:

List<String> list = asList("search string", "searched string", "searched string 2");
List<String result = list.stream()
  .filter(s -> s.contains("searched string")) // lambda to filter the stream
  .map(s -> new StringBuilder(s).reverse().toString()) // lambda to work on each item
  .collect(Collectors.toList());
// here result = ["gnirts dehcraes", "2 gnirts dehcraes"]

However lambda enables you to go further in term of API!

Continue reading