Wednesday Jan 15, 2014

YouTube: Streams, Lambdas, and Method References in Java 8

In this brief and silent YouTube clip, we end with this method, which uses a method reference in a stream:

public synchronized int getNumberOfItems() {

Another way we express the same method is as follows, which uses a lambda in a stream:

public synchronized int getNumberOfItems() {
    return -> x.getQuantity).sum();

And we start with this one:

public synchronized int getNumberOfItems() {

    numberOfItems = 0;

    for (ShoppingCartItem scItem : items) {

        numberOfItems += scItem.getQuantity();


    return numberOfItems;


How to get from the above to the compacter JDK 8 equivalents, via various alternatives, watch the silent movie below.

You'll notice that I keep moving with my mouse into the left sidebar. I do this to show what I'm doing because if I had pressed Alt-Enter each time, to popup the hint suggestions, you wouldn't have seen what I'm doing. In real life, you would press Alt-Enter each time you see the mouse move into the left sidebar above.

And, by the way, what you also see above is that refactoring works across lambdas, streams, method references, and the traditional Java code.

More on lambdas:

More on streams:

More on method references:

Thanks to Ralph Ruijs from the NetBeans Java Editor team for providing this entire sequence, plus a few others, today. A full step by step YouTube movie, with audio explanations of all the code, will follow soon.


Geertjan Wielenga (@geertjanw) is a Principal Product Manager in the Oracle Developer Tools group living & working in Amsterdam. He is a Java technology enthusiast, evangelist, trainer, speaker, and writer. He blogs here daily.

The focus of this blog is mostly on NetBeans (a development tool primarily for Java programmers), with an occasional reference to NetBeans, and sometimes diverging to topics relating to NetBeans. And then there are days when NetBeans is mentioned, just for a change.


« January 2014 »