Saturday, December 7, 2013

A conversational guide for JDK8's lambdas - a glossary of terms

Last advent...I wrote a post related to the new treats that JDK8 has for us. Most probably the feature that I am the most excited about are the lambdas. I have to admit that in my 1st year of being the prodigal soon (during which I have developed using C#), I loved the LINQ and the nice, elegant things you can do with it. Now, even if erasure is still in the same place where we left it the last time, now we have a better way to filter, alter, walk the collections and beside the syntactic sugar, it might also make you use properly the quad core processor that you bragged about to your friends. And talking about friends this post is a cheatsheet of terms related to lambdas and stream processing that you can throw to your friends when they ask you: "What's that <place term from JDK 8 related to lambdas>?". It is not my intent to have a full list or a how-to lambda guide, if I said something wrong or I missed something please let me know...

Functional interface:


According to [jls 8] a functional interface is an interface that has just one abstract method, and thus represents a single function contract (In some cases, this "single" method may take the form of multiple abstract methods with override-equivalent signatures ([jls7_8.4.2]) inherited from superinterfaces; in this case, the inherited methods logically represent a single method).

@FunctionalInterface - is used to indicate that an interface is meant to be a functional interface. If the annotation is placed on an interface that is actually not, a compile time error occurs.

Ex:

interface Runnable { void run(); }

The Runnable interface is a very appropriate example as the only method present is the run method. Another Java "classic" example of functional interface is the Comparator<T> interface, in the following example is a before mentioned interface and the equals method inherited from Object, the interface is still functional as the compare method is the only abstract method, while the equals is inherited from the superclass.


interface Comparator<T> {
  boolean equals(Object obj);

  int compare(T o1, T o2);

}



Stream


stream - according to [oxford dictionary], in computing it is a continuous flow of data or instructions, typically one having a constant or predictable rate.



Starting with JDK 8 stream represents a mechanism used for conveying elements from a data source, through a computational pipeline. A stream can use as data sources arrays, collections, generator functions, I/O channels.



Obtaining streams:


  • From a Collection via the stream() and/or parallelStream() methods;
  • From an array via Arrays.stream(Object[])
  • From static factory methods on the stream classes, such as Stream.of(Object[]), IntStream.range(int, int) or Stream.iterate(Object, UnaryOperator);
  • The lines of a file can be obtained from BufferedReader.lines();
  • Streams of file paths can be obtained from methods in Files;
  • Streams of random numbers can be obtained from Random.ints();
  • Numerous other stream-bearing methods in the JDK, including BitSet.stream(), Pattern.splitAsStream(java.lang.CharSequence), and JarFile.stream().
stream operations - actions taken on the stream. From the point of view of stream manipulation there are two types of actions: intermediate and terminal  operations

stream intermediate operation - operations that are narrowing the content of the stream. Intermediate operations are lazy by nature - do not actually alter the content of the stream, but create another narrower stream. The traversal of the stream begins only when the terminal operation is called.
  •  filter - filters the stream based on the provided predicate
  •  map - creates a new stream by applying the mapping function to each element from the initial stream (corresponding methods for each numeric type: int, long, double)
  •  flatMap - operation that has the effect of applying a one-to-many transformation to the elements of the stream, and then flattening the results elements into a new stream. For example, if orders is a stream of purchase orders, and each purchase order contains a collection of line items, then the following produces a stream of line items:
                     orderStream.flatMap(order -> order.getLineItems().stream())
  • distinct - returns a stream of distinct operations
  • sorted - returns a stream of sorted operations
  • peek - debug focused method that returns a stream consisting of elements of this stream, the provided action is performed on each element
 Ex:


list.stream()
     .filter(filteringFunction)

     .peek(e -> {System.out.println("Filtered value: " + e); });

     .map(mappingFunction)

     .peek(e -> {System.out.println("Mapped value: " + e); });

     .collect(Collectors.intoList());

  • limit - returns a truncated version of the current stream (no more than the limit number of elements)
  • substream - returns a stream consisting of the remaining element starting from startposition, or between startPosition and endPosition

stream terminal operation - traverse the stream to produce a result or a side-effect. After the execution of the terminal operation, the stream is considered
consumed( calling another operation on a consumed stream will throw an IllegalStateException). Terminal operations are eager in nature, with the exception of iterator() and splititerator() that provide an extension mechanism for those that don't find the needed function in the API.
  • forEach - applies the provided operation to every element of the stream. Also the forEachOrdered version exists
  • toArray - extracts the elements of the stream into an array
  • reduce  - reduction method
  • collect - mutable reduction method
  • min     - computes the minimum of the stream
  • max     - computes the maximum of the stream
  • count   - counts the elements of the stream
  • anyMatch - returns true if there is an element matching the provided criteria
  • allMatch - returns true if all the elements match
  • noneMatch - returns true if none of the elements match 
  • findFirst - finds the first element that matches the provided condition
  • findAny - returns an element from the stream


stream pipeline: consists of a source, followed by zero or more intermediate operations and a terminal operation.

spliterator - spliterator for traversing and partinioning elements of a source. One can use it for traverse, estimate element count or split it in multiple spliterators

Reduction - a reduction operation (or fold) takes a sequence of input elements and combines them into a single summary result by repeated application
of a combining operation. A reduction operation can be computing the sum, max, min, count or collecting the elements in a list. The reduction operation
is also parallelizable as long as the function(s) used are associative and stateless. The method used for reduction is reduce()

Ex: reduction using sum:

int sum = numbers.stream().reduce(0, (x,y) -> x + y);

or

int sum = numbers.stream().reduce(0, Integer::sum);

Mutable reduction - is a operation that accumulates input elements into a mutable result container (StringBuilder or Collection) as it processes the elements in
the stream.

Ex: String concatenated = strings.reduce("", String::concat)

Predicate - functional interface that determines whether the input object matches some criteria


I hope you find this condensed list beneficial and you keep it in your bookmarks for those moments when you need all these terms on one page.
If you find something that is missing, please let me know so I can correct it.

So...I wish you a nice Advent Time and a Happy/Jolly/Merry but most important of all I wish you a peaceful Christmas!




 Useful resources:

Most of the information was extracted from [stream]. Particularly useful I found the very comprehensive javadoc of the given classes. 

 [jls7_8.4.2] - http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.4.2

Lambda Related resources on +ManiSarkar's recommendation:

https://github.com/AdoptOpenJDK/lambda-tutorial
http://lambdafaq.com

Meta: this post is part of the Java Advent Calendar and is licensed under the Creative Commons 3.0 Attribution license. If you like it, please spread the word by sharing, tweeting, FB, G+ and so on!

4 comments:

  1. Just did a hands-on session at @java2days in Sofia with the Bulgarian JUG (BGJUG) on #Lamdbas and we used these two sites as our reference: https://github.com/AdoptOpenJDK/lambda-tutorial and http://lambdafaq.com

    Thanks to Olympiu for this article - will make use of it, useful stuff!

    ReplyDelete
    Replies
    1. thank you Mani, I added the resource you point out in the useful resources part - I hope that's OK from your side.

      Delete
    2. My pleasure! Glad you added them, they are very helpful - people must repeatedly go through them - will make them thorough! Had great joy reading your post - very concise!

      Delete
  2. This comment has been removed by the author.

    ReplyDelete