Java SE 8: Standard library Enhancements

Source: Internet
Author: User
Tags foreach arrays count execution iso 8601 join range sort



Lambda expressions are a core feature of Java SE 8, and most of the improvements are spread around lambda expressions. (The jigsaw project has been postponed to Java SE 9.) The contents of the lambda expression are described in the previous article. This article focuses on enhancements to other Java standard libraries that are included in Java SE 8.






Parallel sorting






With the popularity of multi-core CPUs, the standard library implementations of the Java platform also utilize the capabilities of the underlying hardware platform as much as possible to improve performance. The Fork/join framework is introduced as a lightweight parallel task execution engine in Java SE 7. Java SE 8 uses the Fork/join framework in the implementation of some methods of the standard library. The more typical is the new Parallelsort method in the Java.utils.Arrays class. Unlike existing sort methods, the Parallelsort method is implemented using the Fork/join framework. Better performance on multi-core CPU platforms. The following code sorts by using Parallelsort and sort, respectively, for arrays that contain 100 million integers.




Random Random = new Random ();

int count = 100000000;

int[] array = new Int[count];

Arrays.parallelsetall (array, (index)-> random.nextint ());

int[] copy = new Int[count];

System.arraycopy (array, 0, copy, 0, array.length);

Arrays.parallelsort (array);

Arrays.sort (copy);




On my 4-core CPU platform, the Parallelsort and sort methods took 7112 milliseconds and 16777 milliseconds respectively. So the Parallelsort method has much better performance. However, the Parallelsort method has a significant performance boost only when the volume of data is large. When the amount of data is small, the extra overhead of the Fork/join framework itself is sufficient to offset the performance improvements it brings.






Collection Bulk Data operations






In the development of Java application, the operation of the collection is more common. However, in the Java standard library prior to Java SE 8, the operations on the collection are limited and are basically spread around the collection traversal. The Java standard library is relatively weak in this piece relative to other programming languages. The introduction of lambda expressions in Java SE 8 and enhancements to the standard libraries improve this situation. Specifically, in two aspects of the improvement: the first aspect is the operation of the set of methods. Thanks to the introduction of the default method, interfaces in the Java Collection framework can be updated to add more useful ways of doing things, commonly called "filter/map/reduce". The second aspect is the representation of the operation logic of the collection. The newly added operation uses the new functional interface in the Java.util.function package, which makes it easy to use lambda expressions to represent the processing logic of the collection. These two aspects combine to get more intuitive and concise code.






The core of the new collection bulk processing operation is the new Java.util.stream package, the most important of which is the Java.util.stream.Stream interface. The concept of the stream interface resembles a stream in the Java I/O library, representing a sequence of elements that support sequential and parallel operations. Different conversion operations can be performed on the sequence. The elements contained in the sequence can also be consumed to produce the desired results. The stream interface represents only abstraction at the operational level, and is not related to the underlying data store. The usual way is to create the object of the stream interface from the collection, then perform various conversion operations, and finally the result of the execution of the consumption operation.






The operations contained in the stream interface fall into two categories: the first class is the intermediate operations for converting elements in a sequence, such as filter and map. Such intermediate operations are deferred and can cascade together. The second category is the termination operations of elements in the consumption sequence, such as foreach and count. The object cannot be processed again after a termination operation has been performed on the object of a stream interface. This is in line with the general sense of "flow" understanding. The following code gives the basic usage of the filter, map, and reduce operations in the stream interface. The methods in the stream interface use functional interfaces in large quantities and can be easily manipulated using lambda expressions.




IntStream.range(1,10).filter(i -> i % 2 == 0).findFirst().ifPresent(System.out::println);

//Keep even and output the first element

Intstream. Range (1,10). Map (I - > I * 2). Foreach (system. Out:: println); / / multiply all elements by 2 and output




int value = Intstream.range (1). Reduce (0, integer::sum); Sum






The reduce operation of the stream interface also supports a more complex usage, as shown in the following code:




list<string> fruits = arrays.aslist (new string[] {"Apple", "orange", "Pear"});

int totallength = Fruits.stream (). Reduce (0, (sum, str)-> sum + str.length (), integer::sum);

Sum of string Lengths




The reduce method in this way requires 3 parameters, namely the initial value, the cumulative function, and the combined function. The initial value is the starting value of the reduce operation; The cumulative function accumulates part of the result and the new element into a new part of the result combination function combines the two partial result groups into a new partial result, and finally produces the final result. This form of reduce operation can often be simplified into a map operation and another simple reduce operation, as shown in the following code. The effects are the same in both ways, but the following ways are easier to understand.




int totallength = Fruits.stream (). Maptoint (string::length). Reduce (0, integer::sum);




Another special reduce operation is the collect operation. It differs from reduce in that the process of collect operations is to modify a result object. This avoids unnecessary object creation and improves performance. The result in the following code is an object of a StringBuilder class.




StringBuilder uppercase = Fruits.stream (). Collect (Stringbuilder::new, (Builder, str)

-> builder.append ( Str.substring (0, 1). toUpperCase ()), stringbuilder::append);

Capitalize and connect the first letter of the string




Actions in the stream interface can be executed sequentially or in parallel. This is determined when the object of the stream interface is created. For example, the collection interface provides the stream and Parallelstream methods to create objects for the stream interface of two different execution modes. These two different ways can be switched, through the stream interface of the sequential and parallel methods can be completed.






Date and time






The date and time processing APIs in the Java Standard library have been criticized by developers. Most developers will choose a third-party library such as Joda time for substitution. As part of Java SE 8, JSR 310 redefined the new date and time APIs, drawing on best practices in existing Third-party libraries. The new date and time APIs defined in the Java.time package are based on the standard ISO 8601 calendar system.






In the new date and time APIs, the core classes are LocalDateTime, Offsetdatetime, and Zoneddatetime. The LocalDateTime class represents date and time information with no time zone in the ISO 8601 calendar system. The Offsetdatetime class increases the offset from UTC based on the base date and time. The Zoneddatetime class adds relevant information about the time zone. The following code gives the basic usage of the date and time APIs, including the modification, output, and resolution of dates and times.






See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/Java/




Localdatetime.now (). Plusdays (3). Minushours (1). Format (DateTimeFormatter

. Iso_local_date_time); Output date and Time

Zoneddatetime.now (). Withzonesameinstant (Zoneid.of ("gmt+08:00")). Format

( Datetimeformatter.iso_zoned_date_time); Output date, time, and timezone

Datetimeformatter.ofpattern ("yyyy MM DD"). Parse ("200101")

. Query (Temporalquery.localdate ()); Resolution of dates




In addition to the above 3 classes, there are several auxiliary classes worth mentioning.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.