Current location - Loan Platform Complete Network - Big data management - What are the new features of Java 8?
What are the new features of Java 8?

Note that this article is an excerpt from is a featured article in the DZone Guide  to the Java Ecosystem by Trisha Gee, a senior Java engineer and evangelist. In this article, Trisha Gee explains the important features of Java 8 and the reasons to use it, translated by OneAPM engineers.

I. Key Takeaways

1. In many cases, Java 8 can improve application performance without any changes or performance tuning.

2.?Lambda expressions, the Streams API, and new methods for existing classes are all important tools for improving productivity.

3, Java8's new Optional type reduces the likelihood of NullPointerExceptions when dealing with null values, giving developers great flexibility.

Other features:

Faster

One of the major selling points that can please the boss and satisfy the business or operations staff is that Java8 is faster when running applications. Typically, applications upgrading to Java8 get a speed boost, even if they haven't been changed or tuned in any way. This may not apply to applications that have been tuned to cater to a particular JVM. But there are many more reasons why Java8 performance is better:

More than 80% of high-end enterprise applications use the JAVA platform (telecom, banking, etc.) JAVA is a mature product, 10 years old. If you want to build something in the Java industry, want to systematically java learning, then you can come to this group, the front is two-three-one, the middle is three-one-four, the back is zero-two-eight. Connect it up and you're done. There are many Internet bulls here to teach you to learn, and there are free courses. Not want to learn do not add.

Performance Boost for Common Data Structures: Benchmarks of the popular HashMap show that they perform better in Java 8. This kind of boost is very appealing - you don't need to learn a new Streams API or Lambda syntax, or even change your existing code, to improve the performance of your application.

Garbage collector improvements: In general, Java application performance depends on the efficiency of garbage collection. Indeed, poor garbage collection can greatly impact application performance. java8 makes a number of changes to garbage collection that can effectively improve performance and simplify tuning. The most well-known changes are the removal of PermGen and the introduction of Metaspace.

Fork/Join speedup: The fork/join framework was first introduced in Java 7 to simplify concurrent programs using the JVM, and a lot of effort has been put into Java 8 to further improve the framework. Now, fork/join is used for concurrent operations in the Streams API.

In addition, Java8 includes many improvements to support concurrency. oracle summarizes these performance improvements in JDK 8.

Fewer lines of code

Java is often criticized for having too much sample code. In response, the new Java 8 APIs take a more functional approach, focusing on what is implemented rather than how it is implemented.

Lambda Expressions

Lambda expressions in Java8 are not just syntactic icing on top of Java's existing anonymous inner classes - methods that passed behavior before Java8 was introduced. Lambda expressions use internal changes from Java 7 and are therefore quite fluent. To learn how to simplify your code with Lambda expressions, read on.

Introducing New Methods for Collections

Lambda expressions and Streams are probably two of the biggest selling points of Java 8. What's less well known is that Java now allows developers to add new methods to existing classes without having to compromise on backward compatibility. As a result, new methods, combined with Lambda expressions, can greatly simplify code. For example, we often need to determine whether a member of a Map already exists, and if it doesn't, create it. Before Java 8, you might have done this:

private?final?Map<CustomerId,?Customer>?customers?=?new?HashMap<>();?

public?void?incrementCustomerOrders(CustomerId?customerId)? {?

Customer?customer?=?customers.get(customerId);?

if?(customer?==?null)? {?

customer?=?new?Customer(customerId);?

customers.put(customerId,?customer);?

}?

customer.incrementOrders();?

}

The operation "check if a member exists in the map and add it if it doesn't" is so common that Java has now added a new method, computeIfAbsent, to Map to support it. The second argument to this method is a Lambda expression that defines how to create the missing member.

public?void?incrementCustomerOrders(CustomerId?customerId)? {?

Customer?customer?=?customers.computeIfAbsent(customerId,?

id?->?new?Customer(id));?

customer.incrementOrders();?

}

In fact, Java 8 has a new feature called method references that allows us to implement this functionality in more concise code:

public?void?incrementCustomerOrders(CustomerId? customerId)? {?

Customer?customer?=?customer.computeIfAbsent(customerId,?Customer::new);?

customer.incrementOrders();?

}

Java8 adds new methods to both Map and List. You can learn about these new methods and see how many lines of code they save.

Streams API

The Streams API provides more flexibility for querying and manipulating data. It's a very powerful feature. Read these articles to get a more complete understanding of the Streams API. Building smooth data queries in the age of big data can be very interesting and is a common operation. For example, you have a list of books and you want to list the author names of those books in alphabetical order with no duplicates.

public?List<Author>?getAllAuthorsAlphabetically(List<Book>?books)? {?

List<Author>?authors?=?new?ArrayList<>();?

for?(Book?book?:?books)? {?

Author?author?=?book.getAuthor();?

if?(!authors.contains(author))? {?

authors.add(author);?

}?

}?

Collections.sort(authors,?new?Comparator<Author>()? {?

public?int?compare(Author?o1,?Author?o2)? {?

return?o1.getSurname().compareTo(o2.getSurname());?

}?

}});?

return?authors;?

}

In the above code, we first iterate through the list of books and add the author of the book if it never appears in the authors list. After that, we sort the authors alphabetically by their last name. This sorting operation is an area that Streams excels at solving:

public?List<Author>?getAllAuthorsAlphabetically(List<Book>?books)? {?

return?books.Streams()?

.map(book?->?book.getAuthor())?

.distinct()?

.sorted((o1,?o2)? ->?o1.getSurname().compareTo(o2.getSurname()))?

.collect(Collectors.toList());?

}

The above approach is not only fewer lines of code, it's also more descriptive - later developers reading this code will be able to easily understand that 1. the code gets the author's name from the book. 2. it only cares about authors who never appeared in the book. 3. the returned list is sorted by the author's last name. Using the Streams API in conjunction with other new features - method references, new methods for comparators (Comparator) - results in a more concise version:

public?List<Author> ;getAllAuthorsAlphabetically(List<Book>?books)? {?

return?books.Streams()?

.map(Book::getAuthor)?

.map(Book::getAuthor)?

.sorted(Comparator.comparing(Author::getSurname))?

.collect(Collectors.toList());?

}

Here, the sorting method is more obvious by author last name.

Facilitating parallelism

Previously we've talked about better out-of-the-box performance, and in addition to the previously mentioned features, Java8 makes better use of CPU cores. By replacing the Streams method in the previous example with parallelStreams, the JVM breaks this operation into separate tasks and uses fork/join to run these tasks on multiple cores. However, parallelization is not the magic bullet that speeds up all operations. Parallelizing operations always involves more work-decomposing the operations and integrating the results-so it can't always reduce the time. However, for examples where parallelization is appropriate, it is still quite efficient to do so.

Maximizing Null Pointers

Another new feature in Java 8 is the new Optional type. This type means "I may have a value, or I may be null." This minimizes the chance of a NullPointerException by allowing the API to distinguish between a return value that may be null and one that will never be null.

Optional's best use is in dealing with nulls; for example, suppose we want to find a specific book from a list, the newly created findFirst() method returns a value of type Optional, indicating that it can't be sure that a specific value was found. With this optional value, we can then decide what to do if it's a null value. If we want to throw a custom exception, we can use orElseThrow:

public?Book?findBookByTitle(List<Book>?books,?String?title)? {?

Optional<Book>?foundBook?=?books.Streams()?

.filter(book?->?book.getTitle().equals(title))?

.findFirst();?

return?foundBook.orElseThrow(()? ->?new?BookNotFoundException("Did?not?find?book?with?title?"? +?title));?

}

Or, you can return other books:

return?foundBook.orElseGet(()? ->?getRecommendedAlternativeBook(title));

Or, return the Optional type so that the caller of the method can decide for himself what to do if the book is not found.

Summary: Java8, a major release of the Java language, contains syntax changes, new methods and data types, and a number of implicit improvements that silently enhance application performance.Oracle no longer supports Java 7, so many companies have been forced to move to Java8. The good news is that Java 8 is much better for business, for existing applications, and for developers looking to improve productivity.