Category Archives: lambda

JPA + Java8 Stream = paginated findAll()


For batch tasks it is quite common to need to browse a full table. Depending the table it can be done in memory without thinking much or it can be too big and needs pagination.

A common solution was to use a kind of PageResult object which was representing the current page and its index and let the client/caller iterating over PageResults.

With java 8 streams the API can be more concise and efficient.

Continue reading

Advertisements

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