Читаем Introducing Java 8 полностью

Introducing Java 8

Java SE 8 is perhaps the largest change to Java in its history, led by its flagship feature—lambda expressions. If you're an experienced developer looking to adopt Java 8 at work, this short guide will walk you through all of the major changes before taking a deep dive into lambda expressions and Java 8's other big feature: the Streams API.

Raoul-Gabriel Urma

18+

Introducing Java 8

Raoul-Gabriel Urma

Introducing Java 8

by Raoul-Gabriel Urma

Copyright © 2015 O’Reilly Media, Inc. All rights reserved.

Printed in the United States of America.

Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472.

O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (http://safaribooksonline.com). For more information, contact our corporate/institutional sales department: 800-998-9938 or corporate@oreilly.com.

Editors: Nan Barber and Brian Foster

Production Editor: Colleen Lobner

Copyeditor: Lindsy Gamble

Interior Designer: David Futato

Cover Designer: Ellie Volckhausen

Illustrator: Rebecca Demarest

August 2015: First Edition

Revision History for the First Edition

2015-08-20: First Release

2015-09-02: Second Release

Cover photo: Tiger_2898 by Ken_from_MD via flickr, flipped and converted to grayscale. http://www.flickr.com/photos/4675041963_97cd139e83_o.jpg.

The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. Introducing Java 8 and related trade dress are trademarks of O’Reilly Media, Inc.

While the publisher and the author have used good faith efforts to ensure that the information and instructions contained in this work are accurate, the publisher and the author disclaim all responsibility for errors or omissions, including without limitation responsibility for damages resulting from the use of or reliance on this work. Use of the information and instructions contained in this work is at your own risk. If any code samples or other technology this work contains or describes is subject to open source licenses or the intellectual property rights of others, it is your responsibility to ensure that your use thereof complies with such licenses and/or rights.

978-1-491-93434-0

[LSI]

Chapter 1. Java 8: Why Should You Care?

There were two motivations that drove the changes in Java 8:

Better code readability

Simpler support for multicore

Code Readability

Java can be quite verbose, which results in reduced readability. In other words, it requires a lot of code to express a simple concept. Here’s an example: say you need to sort a list of invoices in decreasing order by amount. Prior to Java 8, you’d write code that looks like this: Collections.sort(invoices, new Comparator() { public int compare(Invoice inv1, Invoice inv2) { return Double.compare(inv2.getAmount(), inv1.getAmount()); } });

In this kind of coding, you need to worry about a lot of small details in how to do the sorting. In other words, it’s difficult to express a simple solution to the problem statement. You need to create a Comparator object to define how to compare two invoices. To do that, you need to provide an implementation for the compare method. To read this code, you have to spend more time figuring out the implementation details instead of focusing on the actual problem statement.

In Java 8, you can refactor this code as follows: invoices.sort(comparingDouble(Invoice::getAmount).reversed());

Now, the problem statement is clearly readable. (Don’t worry about the new syntax; I’ll cover that shortly.) That’s exactly why you should care about Java 8—it brings new language features and API updates that let you write more concise and readable code.

Moreover, Java 8 introduces a new API called Streams API that lets you write readable code to process data. The Streams API supports several built-in operations to process data in a simpler way. For example, in the context of a business operation, you may wish to produce an end-of-day report that filters and aggregates invoices from various departments. The good news is that with the Streams API you do not need to worry about how to implement the query itself.

This approach is similar to what you’re used to with SQL. In fact, in SQL you can specify a query without worrying about its internal implementation. For example, suppose you want to find all the IDs of invoices that have an amount greater than 1,000: SELECT id FROM invoices WHERE amount > 1000

This style of writing what a query does is often referred to as declarative-style programming. Here’s how you would solve the problem in parallel using the Streams API: List ids = invoices.stream() .filter(inv -> inv.getAmount() > 1_000) .map(Invoice::getId) .collect(Collectors.toList());

Перейти на страницу:
Нет соединения с сервером, попробуйте зайти чуть позже