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!

Java – far sight look at JDK 8

The world is changing slowly but surely. After the changes that gave java a fresher look with JDK 7, the java community is looking forward to the rest of the improvements that will come with JDK 8 and probably JDK 9. The targeted purpose of JDK 8 was to fill in the gaps in the implementation of JDK 7 – part of the remaining puzzle pieces laking from this implementation, that should be available for the broad audience by in late 2013 is to improve and boost the language in three particular directions:

  • productivity
  • performance
  • modularity

So from next year, java will run everywhere (mobile, cloud, desktop, server etc.), but in an improved manner. In what follows I will provide a short overview of what to expect from 2013 – just in time for New Year’s Resolutions – afterwards I will focus mainly on productivity side with emphasis on project lambda and how will its introduction affect the way we code.

Productivity

In regards of productivity JDK 8 targets two main areas: – collections – a more facile way to interact with collections through literal extensions brought to the language – annotations – enhanced support for annotations, allowing writting them in contexts where are currently illegal (e.g. primitives)

Performance

The addition of the Fork/Join framework to JDK 7, was the first step that java took in the direction of multicore CPUs. JDK 8 takes this road even further by bringing closures’ support to java (lambda expression, that is). Probably the most affected part of java will be the Collections part, the closures combined with the newly added interfaces and functionalities pushing the java containers to the next level. Besides the more readable and shorter code to be written, by providing to the collections a lambda expression that will be executed internally the platform can take advantage of multicore processors.

Modularity

One of the most interresting pieces for the community was project jigsaw: “The goal of this Project is to design and implement a standard module system for the Java SE Platform, and to apply that system to the Platform itself and to the JDK.”. I am using past tense because, for the those of us that were hoping to get rid of the classpaths and classloaders, we have to postpone our exciment for Java 9, as for that point of time was also project jigsaw postponed.
To have a clearer picture of how the remaning Java Roadmap 2013:

2013/01/31 M6 Feature Complete
2013/02/21 M7 Developer Preview
2013/07/05 M8 Final Release Candidate
2013/09/09 GA General Availability

Besides project jigsaw another big and exciting change that will come (in this version), is the support for closures. Provided through the help of lambda expressions they will improve key points of the JDK.

Lambdas

Getting started

First and first of all one should get a lambda enabled SDK. In this direction there are two ways to obtain one:

 * the one intended for the brave ones: build it from the sources 
 * the convenient one: downloading an already compiled version of the SDK 

 Initially I started with building it from the sources, but due to the lack of time and too many warnings related to environment variables, I opted for the lazy approach and took the already existing JDK. The other important tool is a text editor to write the code. As it happened until now, tipically first came the JDK release and after a period of time, an enabled IDE came out. This time it is different, maybe also due to the transparency and the broad availability of the SDK through openjdk. Some days ago, the first Java 8 enabled IDE was realesed by JetBrain. So IntelliJ IDEA version 12 is the first IDE to provide support for JDK 8, besides are improvements? So for testing purposes I used IntelliJ 12 Community Edition together with JDK 8 b68, on a Windows 7, x64 machine. For those of you that prefer Netbeans, a nightly build with lambda support is available for download.

Adjusting to the appropriate mindset.

Before starting to write improved and cleaner code using the newly provided features, one must get a grasp on a couple new concepts – I needed to, anyway.

  • What is a lambda expression? The easiest way to see a lambda expression is just like a method: “it provides a list of formal parameters and a body—an expression or block— expressed in terms of those parameters.The parameters of a lambda expression can be either declared or inferred, when the formal parameters have inferred types, then these types are derived from the functional interface type targeted by the lambda expression. From the point of view of the returned value, a lambda expression can be void compatible – they don’t return anything or value compatible – if any given execution path returns a value.
    Examples of lambda expressions:
    (a) (int a, int b) -> a + b

    (b) (int a, int b) -> {
    if (a > b) {
    return a;
    } else if (a == b) {
    return a * b;
    } else {
    return b;
    }
    }

  • What is a functional interface? A functional interface is an interface that contains just one abstract method, hence represents a single method contract. In some situations, the single method may have the form of multiple methods with override-equivalent signatures, in this case all the methods represent a single method. Besides the typical way of creating an interface instance by creating and instantiating a class, functional interface instances can be created also by usage of lambda expressions, method or constructor references.
    Example of functional interfaces:
    // custom built functional interface
    public interface FuncInterface {
    public void invoke(String s1, String s2);
    }

    Example of functional interfaces from the JAVA API:

      java.lang.Comparable
    java.lang.Runnable
    java.util.concurrent.Callable
    java.awt.event.ActionListener

    So let’s see how the starting of a thread might change in the future:
    OLD WAY:

       new Thread(new Runnable() {
    @Override
    public void run() {
    for (int i=0; i< 9; i++) {
    System.out.println(String.format("Message #%d from inside the thread!", i));
    }
    }
    }).start();

    NEW WAY:

       new Thread(() -> {
    for (int i=0; i< 9; i++) {
    System.out.println(String.format("Message #%d from inside the thread!", i));
    }
    }).start();

    Even if I didn’t write for some time any java Swing, AWT related functionality I have to admit that lambdas will give a breath of fresh air to the Swing developers Action listener addition:

      JButton button = new JButton("Click");

    // NEW WAY:
    button.addActionListener( (e) -> {
    System.out.println("The button was clicked!");
    });

    // OLD WAY:
    button.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
    System.out.println("The button was clicked using old fashion code!");
    }
    });

  • Who/What is SAM? SAM stands for Single Abstract Method, so to cut some corners we can say that SAM == functional interface. Even if in the initial specification, also abstract classes with only one abstract method were considered SAM types, some people found/guessed also the reason why. 
  • Method/Constructor referencing
  • The lambdas sound all nice and all? But somehow the need for functional interface is somehow to some extend restrictive – does this mean that I can use only interfaces that contain a single abstract method? Not really – JDK 8 provides an aliasing mechanism that allows “extraction” of methods from classes or objects. This can be done by using the newly added :: operator. It can be applied on classes – for extraction of static methods or on objects for extraction of methods. The same operator can be used for constructors also.
    Referencing:

    interface ConstructorReference {
    T constructor();
    }

    interface MethodReference {
    void anotherMethod(String input);
    }

    public class ConstructorClass {
    String value;

    public ConstructorClass() {
    value = "default";
    }

    public static void method(String input) {
    System.out.println(input);
    }

    public void nextMethod(String input) {
    // operations
    }

    public static void main(String... args) {
    // constructor reference
    ConstructorReference reference = ConstructorClass::new;
    ConstructorClass cc = reference.constructor();

    // static method reference
    MethodReference mr = cc::method;

    // object method reference
    MethodReference mr2 = cc::nextMethod;

    System.out.println(cc.value);
    }
    }

  • Default methods in interfaces
  • This means that from version 8, java interfaces can contain method bodies, so to put it simple java will support multiple inheritance without the headaches that usually come with it. Also, by providing default implementations for interface methods one can assure ensure that adding a new method will not create chaos in the implementing classes. JDK 8 added default methods to interfaces like java.util.Collection or java.util.Iterator and through this it provided a mechanism to better use lambdas where it is really needed.
    Notable interfaces added:

       java.util.stream.Streamable
    java.util.stream.Stream

    Improved collections’ interaction In my opinion all the changes that come with project lambda are great additions to the language, that will make it align with the current day standards and make it simpler and leaner but probably the change that will have the biggest productivity impact and the biggest cool + wow effect is definitely the revamping of the collections framework. No, there is no Collection 2 framework, we still have to cope with type erasure for now, but java will make another important shift: from external to internal iteration. By doing so, it provides the developer the mechanism to filter and aggregate collections in an elegant manner and besides this to push for more efficiency. By providing a lambda expression that will be executed internally, so multicore processors can be used to their full power. Let’s consider the following scenarios:
    a. Considering a list of strings, select all of them that are uppercased written. How would this be written? OLD WAY:

      
    //.....

    List inputList = new LinkedList<>();
    List upper = new LinkedList<>();

    // add elements

    for (String currentValue : inputList) {
    if (currentValue != null && currentValue.matches("[A-Z0-9]*")) {
    upper.add(currentValue);
    }
    }

    System.out.println(upper);

    //….. NEW WAY:

      
    //.....
    inputList.stream().filter(x -> (x != null && x.matches("[A-Z0-9]*"))).into(upper);


    b. Consider that you would like to change all the extracted characters to lowercase. Using the JDK8 way this would look like this:

     
    // .....
    inputList.stream().filter(x -> (x != null && x.matches("[A-Z0-9]*"))).map(String::toLowerCase).into(upper);


    c. And how about finding out the number of characters from the selected collection

     
    // .....

    int sumX = inputList.stream().filter(x -> (x != null && x.matches("[A-Z0-9]*"))).map(String::length).reduce(0, Integer::sum);

    Used methods:

     default Stream stream() // java.util.Collection
    Stream filter(Predicate predicate) // java.util.stream.Stream
    IntStream map(IntFunction mapper) //java.util.stream.Stream


    d. What if I would like to take each element from a collection and print it?

     //OLD WAY:
    for (String current : list) {
    System.out.println(current);
    }

    //NEW WAY:
    list.forEach(x -> System.out.println(x));


    Besides the mentioned functionality, JDK 8 has are other interesting news also, but for brevity reasons I will stop here. More information about it can be found on the JDK 8 Project lambda site or the webpage of the JSR 337.
    To conclude, Java is moving forward and I personally like the direction it is heading, another point of interest would be to point of time when library developers start adopting JDK 8 too. That will be for sure interesting. Thank you for your time and patience, I wish you a merry Christmas.

    Resources

    Brian Goetz resource folder: http://cr.openjdk.java.net/~briangoetz/lambda
    Method/constructor references: http://doanduyhai.wordpress.com/2012/07/14/java-8-lambda-in-details-part-iii-method-and-constructor-referencing

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! Want to write for the blog? We are looking for contributors to fill all 24 slot and would love to have your contribution! Contact Attila Balazstocontribute!
Disclaimer: This post was based on the JDK8 lambda enabled SDK from 15. December 2012, some features might be subject to change.