Java 8 streams and lambdas

You might not be familiar with lambdas yet. In Java 8, every collection gets a default method stream(), which gives access to functional-style operations.

These operations can be either intermediate operations returning a stream, and thus allowing chaining, or a terminal operation that returns a value.

The most famous intermediate operations are as follows:

  • map: This applies a method to every element of a list and returns the list of results
  • filter: This returns a list of every element matching a predicate
  • reduce: This projects a list into a single value using an operation and an accumulator

Lambdas are shorthand syntax for function expressions. They can be coerced into a Single Abstract Method, an interface with only one function.

For instance, you can implement the Comparator interface as follows:

Comparator<Integer> c = (e1, e2) -> e1 - e2;

Within lambdas, the return keyword is implicitly its last expression.

The double colon operator we used earlier is a shortcut to get a reference to a function on a class,

Tweet::getText

The preceding is equivalent to the following:

(Tweet t) -> t.getText()

The collect method allows us to call a terminal operation. The Collectors class is a set of terminal operations that will put results into lists, sets, or maps, allowing grouping, joining, and so on.

Calling the collect(Collectors.toList()) method will produce a list with every element within the stream; in our case, the tweet names.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.58.5.57