it-ebooks - Modern Java - A Guide to Java 8
Here you can read online it-ebooks - Modern Java - A Guide to Java 8 full text of the book (entire story) in english for free. Download pdf and epub, get meaning, cover and reviews about this ebook. year: 2016, publisher: iBooker it-ebooks, genre: Computer. Description of the work, (preface) as well as reviews are available. Best literature library LitArk.com created for fans of good reading and offers a wide selection of genres:
Romance novel
Science fiction
Adventure
Detective
Science
History
Home and family
Prose
Art
Politics
Computer
Non-fiction
Religion
Business
Children
Humor
Choose a favorite category and find really read worthwhile books. Enjoy immersion in the world of imagination, feel the emotions of the characters or learn something new for yourself, make an fascinating discovery.
Modern Java - A Guide to Java 8: summary, description and annotation
We offer to read an annotation, description, summary or preface (depends on what the author of the book "Modern Java - A Guide to Java 8" wrote himself). If you haven't found the necessary information about the book — write in the comments, we will try to find it.
Modern Java - A Guide to Java 8 — read online for free the complete book (whole text) full work
Below is the text of the book, divided by pages. System saving the place of the last page read, allows you to conveniently read the book "Modern Java - A Guide to Java 8" online for free, without having to search again every time where you left off. Put a bookmark, and you can go to the page where you finished reading at any time.
Font size:
Interval:
Bookmark:
Java is still not deadand people are starting to figure that out.
Welcome to my introduction to Java 8. This tutorial guides you step by step through all new language features. Backed by short and simple code samples you'll learn how to use default interface methods, lambda expressions, method references and repeatable annotations. At the end of the article you'll be familiar with the most recent API changes like streams, functional interfaces, map extensions and the new Date API. No walls of text, just a bunch of commented code snippets. Enjoy!
This article was originally posted on my blog. You should follow me on Twitter.
Java 8 enables us to add non-abstract method implementations to interfaces by utilizing the default
keyword. This feature is also known as virtual extension methods.
Here is our first example:
interface Formula { double calculate ( int a) ; default double sqrt ( int a) { return Math.sqrt(a); }}
Besides the abstract method calculate
the interface Formula
also defines the default method sqrt
. Concrete classes only have to implement the abstract method calculate
. The default method sqrt
can be used out of the box.
Formula formula = new Formula() { @Override public double calculate ( int a) { return sqrt(a * ); }};formula.calculate(); // 100.0 formula.sqrt(); // 4.0
The formula is implemented as an anonymous object. The code is quite verbose: 6 lines of code for such a simple calculation of sqrt(a * 100)
. As we'll see in the next section, there's a much nicer way of implementing single method objects in Java 8.
Let's start with a simple example of how to sort a list of strings in prior versions of Java:
List names = Arrays.asList( "peter" , "anna" , "mike" , "xenia" );Collections.sort(names, new Comparator() { @Override public int compare (String a, String b) { return b.compareTo(a); }});
The static utility method Collections.sort
accepts a list and a comparator in order to sort the elements of the given list. You often find yourself creating anonymous comparators and pass them to the sort method.
Instead of creating anonymous objects all day long, Java 8 comes with a much shorter syntax, lambda expressions:
Collections.sort(names, (String a, String b) -> { return b.compareTo(a);});
As you can see the code is much shorter and easier to read. But it gets even shorter:
Collections.sort(names, (String a, String b) -> b.compareTo(a));
For one line method bodies you can skip both the braces {}
and the return
keyword. But it gets even shorter:
names.sort((a, b) -> b.compareTo(a));
List now has a sort
method. Also the java compiler is aware of the parameter types so you can skip them as well. Let's dive deeper into how lambda expressions can be used in the wild.
How does lambda expressions fit into Java's type system? Each lambda corresponds to a given type, specified by an interface. A so called functional interface must contain exactly one abstract method declaration. Each lambda expression of that type will be matched to this abstract method. Since default methods are not abstract you're free to add default methods to your functional interface.
We can use arbitrary interfaces as lambda expressions as long as the interface only contains one abstract method. To ensure that your interface meet the requirements, you should add the @FunctionalInterface
annotation. The compiler is aware of this annotation and throws a compiler error as soon as you try to add a second abstract method declaration to the interface.
Example:
@FunctionalInterface interface Converter < F , T > { T convert (F from) ;}
Converter converter = (from) -> Integer.valueOf(from);Integer converted = converter.convert( "123" );System.out.println(converted); // 123
Keep in mind that the code is also valid if the @FunctionalInterface
annotation would be omitted.
The above example code can be further simplified by utilizing static method references:
Converter converter = Integer::valueOf;Integer converted = converter.convert( "123" );System.out.println(converted); // 123
Java 8 enables you to pass references of methods or constructors via the ::
keyword. The above example shows how to reference a static method. But we can also reference object methods:
class Something { String startsWith (String s) { return String.valueOf(s.charAt()); }}
Something something = new Something();Converter converter = something::startsWith;String converted = converter.convert( "Java" );System.out.println(converted); // "J"
Let's see how the ::
keyword works for constructors. First we define an example bean with different constructors:
class Person { String firstName; String lastName; Person() {} Person(String firstName, String lastName) { this .firstName = firstName; this .lastName = lastName; }}
Next we specify a person factory interface to be used for creating new persons:
interface PersonFactory < P extends Person > { P create (String firstName, String lastName) ;}
Instead of implementing the factory manually, we glue everything together via constructor references:
PersonFactory personFactory = Person:: new ;Person person = personFactory.create( "Peter" , "Parker" );
We create a reference to the Person constructor via Person::new
. The Java compiler automatically chooses the right constructor by matching the signature of PersonFactory.create
.
Accessing outer scope variables from lambda expressions is very similar to anonymous objects. You can access final variables from the local outer scope as well as instance fields and static variables.
We can read final local variables from the outer scope of lambda expressions:
final int num = ;Converter stringConverter = (from) -> String.valueOf(from + num);stringConverter.convert(); // 3
But different to anonymous objects the variable num
does not have to be declared final. This code is also valid:
int num = ;Converter stringConverter = (from) -> String.valueOf(from + num);stringConverter.convert(); // 3
However num
must be implicitly final for the code to compile. The following code does not compile:
int num = ;Converter stringConverter = (from) -> String.valueOf(from + num);num = ;
Writing to num
from within the lambda expression is also prohibited.
In contrast to local variables, we have both read and write access to instance fields and static variables from within lambda expressions. This behaviour is well known from anonymous objects.
class Lambda4 { static int outerStaticNum; int outerNum; void testScopes () { Converter stringConverter1 = (from) -> { outerNum = ; return String.valueOf(from); }; Converter stringConverter2 = (from) -> { outerStaticNum = ; return String.valueOf(from); }; }}
Remember the formula example from the first section? Interface Formula
Font size:
Interval:
Bookmark:
Similar books «Modern Java - A Guide to Java 8»
Look at similar books to Modern Java - A Guide to Java 8. We have selected literature similar in name and meaning in the hope of providing readers with more options to find new, interesting, not yet read works.
Discussion, reviews of the book Modern Java - A Guide to Java 8 and just readers' own opinions. Leave your comments, write what you think about the work, its meaning or the main characters. Specify what exactly you liked and what you didn't like, and why you think so.