Home > Articles > Programming > Java

Java SE 8: Why Should I Care?

  • Print
  • + Share This
Java retains its object-oriented roots, but has added many functional programming constructs to help it better manage parallel processing. Java expert Steven Haines reviews the must-know features added to Java SE 8.

Like this article? We recommend

Java SE 8 may be one of the most profound Java releases in its 14-year history. When Java was released in 1996 and adopted by the masses in the form of applets (and later Servlets, JSP, and even user interfaces), the consumer computer world was a different place. Most of us had a single CPU in our computers with a single core. Java worked well on a single CPU and, as time and technology evolved, we developed ways to manage concurrency. Java was multi-threaded from its inception, and it implemented a lock-based synchronization strategy for managing access to shared data.

But that was then, this is now. Most of us have multiple CPUs with multiple cores on our desktops, and our servers have even more power. Furthermore, with the advent of the cloud, distributed and parallel computing have grown at an unprecedented rate. In order to stay current with the times, parallel computing requires a paradigm shift away from traditional object-oriented programming to a more functional model. Thus, in the past few years we have seen the evolution of new functional programming languages like Scala and Haskel, as well as the reemergence of older functional programming languages like Erlang.

So what is to become of Java? Java has had a rich history, but if it is to continue to be the language of choice of the mainstream commercial world, it must evolve. And with Java 8, evolve it has!

This article is not exhaustive in its review of the new features added to Java SE 8 (you can read a more exhaustive article series here), but it highlights the specific subset of features that modernize the Java programming language with functional programming concepts to allow it meet the demands of modern computing. In other words, if you are going to stay relevant as a Java programmer in the coming years, then these are the new features in Java that you need to understand.

Java Methods and Functions

We are familiar with passing variables and values to methods, but Java 8 permits methods and functions to be passed to methods as well. This allows you to write a generic method and pass in code that allows it to build a specific result. For example, consider a list of cars. If we want to filter the list of cars to include only coupes or only sedans, we can define methods that perform this check for us. Listing 1 shows a Car class with two static methods that determine if a car is a coupe or a sedan.

Listing 1. Car.java

public class Car {
  public static Boolean isSedan( Car car ) {
    return car.getType().equals( "sedan" );
  }
  public static Boolean isCoupe( Car car ) {
    return car.getType().equals( "coupe" );
  }
}

Listing 1 shows a snippet from the Car class that contains two methods which, when provided with a Car, interpret the type: isSedan() returns true if the type is a “sedan” and isCoupe() returns true if the type is a “coupe”. Listing 2 shows the filter() method from a CarInventory class that manages a list of cars.

Listing 2. CarInventory.java

public class CarInventory {
  public List<Car> filter( Predicate<Car> p ) {
    List<Car> results = new ArrayList<Car>();
    for( Car car : carList ) {
      if( p.test( car ) ) {
        results.add( car );
      }
    }
  return results;
  }
}

The filter() method iterates over a list of cars and builds a result that matches the predicate condition. This probably leads to the question, what is a Predicate? The Predicate interface is defined in the java.util.function package and looks similar to Listing 3.

Listing 3. Predicate.java

public interface Predicate<T> {
  public boolean test( T t );
}

A predicate, in mathematics, is a function that accepts a value and returns true or false. Predicate<Car> could likewise have been written as Function<Car,Boolean>, but Predicate<Car> is more succinct.

Finally, Listing 4 shows how you can pass the correct Car method to the CarInventory filter() method.

Listing 4. Using the filter() method

CarInventory carInventory = new CarInventory();
List<Car> coupes = carInventory.filter( Car::isCoupe );
List<Car> sedans = carInventory.filter( Car::isSedan );

Using the “::” operator, we are able to pass a method to the filter() method and, as we say in Listing 2, that method will be executed inside the filter() method itself.

It does become burdensome to write static methods in our classes just to be passed as predicates, so we have the option to instead create anonymous functions, which are also called lambdas. Lambdas, in general are defined as follows:

( Input values ) -> Expression that optionally produces a response

Given an input, a lambda can do something, which may produce an output. Predicates are special types of lambdas that are of the following form:

( Input values ) -> Expression that evaluates to a boolean

For example, we could retrieve our coupes and sedans as follows:

List<Car> coupes = carInventory.filter( ( Car c ) -> c.getType().equals( "coupe" ) );
List<Car> sedans = carInventory.filter( ( Car c ) -> c.getType().equals( "sedan" ) );

These expressions read as follows: Given a Car c, return true of the type is a “coupe” (or “sedan”). This is functionally equivalent to passing the method (Car::isCoupe).

Streams

Anonymous functions, or lambda expressions, are nice, but they were included in Java 8 for more than syntactic eye candy. In order to better facilitate parallel processing, Java 8 introduced the Streams API, which we will see works hand-in-hand with lambda expressions.

The Streams API allows you to connect multiple methods together such that the output from one method serves as the input to the next method. Furthermore, one method does not have to complete before its output can be used by the next method in the stream. Consider how streams work on a simple Linux command line:

ls –l | grep txt 

ls –l retrieves a list of filenames in the current directory, and then grep txt only shows files that have the string “txt” in their name. ls –l returns filenames one at a time, so if the first file is “file1.txt” then the grep command will process that filename potentially before ls –l returns the second filename. The Streams API follows this model and, if you allow it to, it can execute operations in parallel. For example, if it is performing operations against a collection of elements, it could process more than one record at a time.

Because Java applications frequently operate on collections of data, Streams are intimately connected to Collection classes. Two new methods have been added to the Collection APIs:

  • stream(): Creates a Stream object that can be used to operate on the collection.
  • parallelStream(): Creates a Stream object that can be used to operate on the collection in parallel.

With a Stream in hand, you can execute one of the following methods (the following is a subset of methods that I find most interesting), passing it a lambda expression:

  • filter(): Only passes values that match the supplied predicate to the next stream.
  • distinct(): Ensures that all values in the stream are distinct; in other words if “apple” appears twice, only one “apple” will be passed to the next stream.
  • limit(): Only passes the first n elements to the next stream; for example, limit(3) would only pass the first three elements to the next stream.
  • sorted(): Sorts the items in the stream into their natural order.
  • max()/min(): Returns the maximum or minimum element in the stream.
  • forEach(): Does not return a stream, but instead allows you to perform an operation on every element in the stream.
  • collect(): Ends the stream processing and returns the completed stream in a more consumable fashion, such as a List.

With this description, we could rewrite our coupe/sedan search as follows:

List<Car> cars = new ArrayList<Car>();
// Add cars to the list...

List<Car> coupes = cars.stream().filter(( Car c ) -> c.getType().equals( "coupe" ) )
                                .collect( toList() );
List<Car> sedans = cars.stream().filter(( Car c ) -> c.getType().equals( "sedan" ) )
                                .collect( toList() );

The stream() method converts the List to a Stream (or more specifically, it provides Stream access to the List), the filter() method accepts the predicate that compares the car type to the string “coupe” or “sedan”, and finally the collect() method converts the result to a List. Likewise, if we wanted to find all coupes, but perform the operation in parallel, we could do so with the following command:

List<Car> coupes = cars.parallelStream().filter(( Car c ) -> c.getType().equals( "coupe" ) )
                                .collect( toList() );

parallelStream() provides a Stream that can read the collection, but the JVM can now execute the filter in parallel (on multiple cores on multiple CPUs) and then collect the results into a single list. If our cars List had millions of cars in it, a parallel stream could process the list much faster than a standard stream. The Streams API has the option to create as many threads as it deems necessary and partition the cars into sub-lists for parallel processing. And, as a Java programmer, you are able to gain this level of parallel processing by invoking the parallelStream() method instead of the stream() method. Think about how complicated the code that you would have to write would be to partition the list into sub-lists, create multiple threads and assign each thread a sub-list to process, and then correlate the results into a single response. I hope you can appreciate the value that the Streams API offers.

Returning to our example, if we want to get a little crazy, let’s combine some of the Stream methods to return the five least expensive red coupes:

List<Car> coupes = cars.parallelStream().filter(( Car c ) -> c.getType().equals( "coupe" ) )
                                .filter( ( Car c ) -> c.getColor().equals( "red" ) )
                                .sorted( comparing( Car::getPrice ) )
                                .limit( 5 )
                                .collect( toList() );

The first filter returns only coupes, and the second filter returns only red cars (and yes, you could combine both of these filters into one predicate). Next, we sort the stream by price. The Comparator class now has a static comparing() method to which we can pass a function. In this case, we pass a reference to the Car class’s getPrice() method. The natural sorting order for numbers is lowest to highest, so this will sort the cars by ascending price. Next, we invoke limit(5), which returns only the first five elements in the stream (again, sorted by ascending price). Finally, we call collect() to build a List that contains our five cars.

You may have noticed that Streams allow you to manipulate collections in a declarative way, or in other words, they allow you to define the type of operation to perform on the collection without having to write all of the plumbing code to make it work. Furthermore, when the Streams API is used in parallel, it not only dramatically improves performance, but also removes some very complicated plumbing code!

This section only touched on the Streams API, but hopefully it has whet your appetite to learn more.

Static Interface Methods and Default Methods

Before leaving this introduction to Java 8, I thought it important to review two additional features that enabled the developers at Oracle to update the collection APIs without breaking a horde of existing code. In addition to the standard collection classes, various developers have built implementations of the collection classes, but adhered to the interfaces to ensure compatibility. Should Oracle have required all of them to update their code to add the new stream() and parallelStream() methods? In Java 7, they would have no choice. So in Java 8, Oracle added the following two capabilities:

  • Static interface methods
  • Default interface methods

Java 8 allows you to implement static methods in your interfaces. In Java 7, all method implementations, static or not static, needed to be implemented in classes. Now you are free to implement static methods in interfaces.

Similarly, interfaces are now able to implement default methods, using the new default keyword. For example, the Collection<E> interface that all collection classes implement (ArrayList, TreeSet, etc.) defines a new default method called stream() that returns “a sequential Stream over the elements in this collection.” This means that any collection class that implements the Collection interface can now be used through the Streams API framework. The stream() method is defined as follows:

public interface Collection<E> {
  ...
  default Stream<E> stream() {
    // Build the stream...
  }
}

In addition to defining methods that collection classes must implement, the Collection interface was able to build the implementation of the stream() method for those classes. Classes that implement the Collection interface are free to override the stream() method, but if they do not, then the default implementation will be used. Whether or not you will leverage this feature in your code has yet to be seen, but it is what empowered Oracle to make changes without breaking existing code.

Summary

As computer hardware has evolved, functional programming languages have slowly replaced object-oriented programming languages because of their ability to operate on multiple CPUs and multiple cores. Java has a rich history, and has become the dominant choice of commercial enterprises, but if it does not evolve then it can be replaced. Fortunately, when designing Java 8, Oracle saw this disparity and added functional programming capabilities to Java.

This article provided a high-level overview of some of the more important features introduced in Java 8 that support functional programming paradigms. Specifically this article reviewed:

  • Passing functions to methods, as well as defining anonymous functions (lambdas) and passing those to methods
  • The Streams API, which is used to perform parallel operations without requiring the programmer to write complicated threading code
  • Static and default interface methods, which allow developers to provide default implementations of methods in interfaces

This article has been only a small introduction. For more details about the specific features in Java 8, refer to this article series Java SE 8's New Language Features.

  • + Share This
  • 🔖 Save To Your Account

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020