KK

Java 8: Lambdas & streams

August 1, 2017

How two language features kept Java modern


2004, that was then …

In October 2004 when Java 5 was released, Perl was still a necessary evil, Amazon was a month from releasing it’s first AWS product (along side Alexa’s birth) and Java’s legitimacy as a C++ contender was still hotly contested.

Java 5 was packed with features that are now indispensable: the concurrency package, enums, generics, autoboxing and annotations. With its continual performance improvements, Java’s adoption rates continued to accelerate.

… This is now

Since October 2004, Node.js changed expectations on client-server connection management (2009), Ruby on Rails showed off Ruby’s tight easy to read syntax (2004) and Apple’s choice of Objective-C (later Swift) for building iPhone apps (2008) put lambdas in the spotlight.

While Java 6 and 7 was giving us tweaks like “allowing underscores in numeric literals” and “strings in switch statements,” a hoard of state of the art modern programming languages were developed giving the market an unprecedented number of legitimate alternatives.

Streams and Lambdas

If you want to do some work parallel, you may imagine a few ways of doing it using Executors and Callables, but here is how it’s done in Java 8:

IntStream
  .range(0, 5)
  .parallel()
  .forEach( (i) -> {
    // The "Lambda"
    System.out.println(
      "Working on item: " + i
    + " in thread: "
    + Thread
        .currentThread()
        .getId());
    });

Which gives the output:

Working on item: 4 in thread: 1
Working on item: 2 in thread: 1
Working on item: 1 in thread: 9
Working on item: 3 in thread: 9
Working on item: 4 in thread: 10
Working on item: 0 in thread: 1

Going from Java 7, this is huge step forward. In an easy, compact and readable form we:

  1. Loop over the values from 0 to 4.
  2. Perform some fixed work for each value without any class declarations.
  3. Do it in parallel without doing any explicit thread management!

Just the tip of the iceberg

Using streams and lambdas you can do things like filter, sort, transform in parallel with ease. In combination with a few of the other changes released with Java 8, it has the potential to speed up your development while writing faster and more maintainable code.

Conclusion

Some believe that Java 8 was too little too late, but after a few years of seeing what it can do, I disagree. Before streams, parallelism and lambdas were introduced, languages like Scala had something significant over Java, but that hasn’t been the case since 2014. There are still differences, but the debate has become religious. You can still save a few lines here and there with other languages, but the objective is effective code that’s easy to understand. Java Brains has a good onboarding to lambdas in Java.