Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Modern Java - A Guide to Java 8

License

NotificationsYou must be signed in to change notification settings

w17731138318/java8-tutorial

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

“Java is still not dead—and people are starting to figure that out.”

这是对(https://github.com/winterbe/java8-tutorial) 的中文翻译

如果对你有帮助,请到(https://github.com/winterbe/java8-tutorial) 赏原作者一个Start★

No walls of text, just a bunch of commented code snippets. Enjoy!

没有文字,只有一堆注释的代码片段。请享受!

内容

接口的默认方法

Java 8 enables us to add non-abstract method implementations to interfaces by utilizing thedefault keyword. This feature is also known asvirtual extension methods.

Here is our first example:

interfaceFormula {doublecalculate(inta);defaultdoublesqrt(inta) {returnMath.sqrt(a);    }}

Besides the abstract methodcalculate the interfaceFormula also defines the default methodsqrt. Concrete classes only have to implement the abstract methodcalculate. The default methodsqrt can be used out of the box.

Formulaformula =newFormula() {@Overridepublicdoublecalculate(inta) {returnsqrt(a *100);    }};formula.calculate(100);// 100.0formula.sqrt(16);// 4.0

The formula is implemented as an anonymous object. The code is quite verbose: 6 lines of code for such a simple calculation ofsqrt(a * 100). As we'll see in the next section, there's a much nicer way of implementing single method objects in Java 8.

Lambda 表达式

Let's start with a simple example of how to sort a list of strings in prior versions of Java:

List<String>names =Arrays.asList("peter","anna","mike","xenia");Collections.sort(names,newComparator<String>() {@Overridepublicintcompare(Stringa,Stringb) {returnb.compareTo(a);    }});

The static utility methodCollections.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, (Stringa,Stringb) -> {returnb.compareTo(a);});

As you can see the code is much shorter and easier to read. But it gets even shorter:

Collections.sort(names, (Stringa,Stringb) ->b.compareTo(a));

For one line method bodies you can skip both the braces{} and thereturn keyword. But it gets even shorter:

names.sort((a,b) ->b.compareTo(a));

List now has asort 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 calledfunctional interface must containexactly 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:

@FunctionalInterfaceinterfaceConverter<F,T> {Tconvert(Ffrom);}
Converter<String,Integer>converter = (from) ->Integer.valueOf(from);Integerconverted =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<String,Integer>converter =Integer::valueOf;Integerconverted =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:

classSomething {StringstartsWith(Strings) {returnString.valueOf(s.charAt(0));    }}
Somethingsomething =newSomething();Converter<String,String>converter =something::startsWith;Stringconverted =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:

classPerson {StringfirstName;StringlastName;Person() {}Person(StringfirstName,StringlastName) {this.firstName =firstName;this.lastName =lastName;    }}

Next we specify a person factory interface to be used for creating new persons:

interfacePersonFactory<PextendsPerson> {Pcreate(StringfirstName,StringlastName);}

Instead of implementing the factory manually, we glue everything together via constructor references:

PersonFactory<Person>personFactory =Person::new;Personperson =personFactory.create("Peter","Parker");

We create a reference to the Person constructor viaPerson::new. The Java compiler automatically chooses the right constructor by matching the signature ofPersonFactory.create.

Lambda 作用域

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:

finalintnum =1;Converter<Integer,String>stringConverter =        (from) ->String.valueOf(from +num);stringConverter.convert(2);// 3

But different to anonymous objects the variablenum does not have to be declared final. This code is also valid:

intnum =1;Converter<Integer,String>stringConverter =        (from) ->String.valueOf(from +num);stringConverter.convert(2);// 3

Howevernum must be implicitly final for the code to compile. The following code doesnot compile:

intnum =1;Converter<Integer,String>stringConverter =        (from) ->String.valueOf(from +num);num =3;

Writing tonum 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.

classLambda4 {staticintouterStaticNum;intouterNum;voidtestScopes() {Converter<Integer,String>stringConverter1 = (from) -> {outerNum =23;returnString.valueOf(from);        };Converter<Integer,String>stringConverter2 = (from) -> {outerStaticNum =72;returnString.valueOf(from);        };    }}

访问方法的默认接口

Remember the formula example from the first section? InterfaceFormula defines a default methodsqrt which can be accessed from each formula instance including anonymous objects. This does not work with lambda expressions.

Default methodscannot be accessed from within lambda expressions. The following code does not compile:

Formulaformula = (a) ->sqrt(a *100);

内置功能接口

The JDK 1.8 API contains many built-in functional interfaces. Some of them are well known from older versions of Java likeComparator orRunnable. Those existing interfaces are extended to enable Lambda support via the@FunctionalInterface annotation.

But the Java 8 API is also full of new functional interfaces to make your life easier. Some of those new interfaces are well known from theGoogle Guava library. Even if you're familiar with this library you should keep a close eye on how those interfaces are extended by some useful method extensions.

Predicates

Predicates are boolean-valued functions of one argument. The interface contains various default methods for composing predicates to complex logical terms (and, or, negate)

Predicate<String>predicate = (s) ->s.length() >0;predicate.test("foo");// truepredicate.negate().test("foo");// falsePredicate<Boolean>nonNull =Objects::nonNull;Predicate<Boolean>isNull =Objects::isNull;Predicate<String>isEmpty =String::isEmpty;Predicate<String>isNotEmpty =isEmpty.negate();

Functions

Functions accept one argument and produce a result. Default methods can be used to chain multiple functions together (compose, andThen).

Function<String,Integer>toInteger =Integer::valueOf;Function<String,String>backToString =toInteger.andThen(String::valueOf);backToString.apply("123");// "123"

Suppliers

Suppliers produce a result of a given generic type. Unlike Functions, Suppliers don't accept arguments.

Supplier<Person>personSupplier =Person::new;personSupplier.get();// new Person

Consumers

Consumers represent operations to be performed on a single input argument.

Consumer<Person>greeter = (p) ->System.out.println("Hello, " +p.firstName);greeter.accept(newPerson("Luke","Skywalker"));

Comparators

Comparators are well known from older versions of Java. Java 8 adds various default methods to the interface.

Comparator<Person>comparator = (p1,p2) ->p1.firstName.compareTo(p2.firstName);Personp1 =newPerson("John","Doe");Personp2 =newPerson("Alice","Wonderland");comparator.compare(p1,p2);// > 0comparator.reversed().compare(p1,p2);// < 0

Optionals

Optionals 来历

到目前为止,臭名昭著的空指针异常是导致Java应用程序失败的最常见原因。以前,为了解决空指针异常,Google公司著名的Guava项目引入了Optional类,Guava通过使用检查空值的方式来防止代码污染,它鼓励程序员写更干净的代码。受到Google Guava的启发,Optional类已经成为Java 8类库的一部分。

Optional实际上是个容器:它可以保存类型T的值,或者仅仅保存null。Optional提供很多有用的方法,这样我们就不用显式进行空值检测。更多详情请参考官方文档。

原文翻译

Optionals 不是功能接口,但能极好而有效的防止NullPointerException。这是下一节的一个重要概念,所以让我们看看如何使用。

Optional 被定义为一个简单的容器,其值可能是null或者不是null。在Java 8之前一般某个函数应该返回非空对象但是偶尔却可能返回了null,而在Java 8中,不推荐你返回null而是返回Optional。

Optional<String>optional =Optional.of("bam");optional.isPresent();// trueoptional.get();// "bam"optional.orElse("fallback");// "bam"optional.ifPresent((s) ->System.out.println(s.charAt(0)));// "b"

Streams

Ajava.util.Stream represents a sequence of elements on which one or more operations can be performed. Stream operations are eitherintermediate orterminal. While terminal operations return a result of a certain type, intermediate operations return the stream itself so you can chain multiple method calls in a row. Streams are created on a source, e.g. ajava.util.Collection like lists or sets (maps are not supported). Stream operations can either be executed sequentially or parallely.

Streams are extremely powerful, so I wrote a separateJava 8 Streams Tutorial. You should also check outStream.js, a JavaScript port of the Java 8 Streams API.

Let's first look how sequential streams work. First we create a sample source in form of a list of strings:

List<String>stringCollection =newArrayList<>();stringCollection.add("ddd2");stringCollection.add("aaa2");stringCollection.add("bbb1");stringCollection.add("aaa1");stringCollection.add("bbb3");stringCollection.add("ccc");stringCollection.add("bbb2");stringCollection.add("ddd1");

Collections in Java 8 are extended so you can simply create streams either by callingCollection.stream() orCollection.parallelStream(). The following sections explain the most common stream operations.

Filter

Filter accepts a predicate to filter all elements of the stream. This operation isintermediate which enables us to call another stream operation (forEach) on the result. ForEach accepts a consumer to be executed for each element in the filtered stream. ForEach is a terminal operation. It'svoid, so we cannot call another stream operation.

stringCollection    .stream()    .filter((s) ->s.startsWith("a"))    .forEach(System.out::println);// "aaa2", "aaa1"

Sorted

Sorted is anintermediate operation which returns a sorted view of the stream. The elements are sorted in natural order unless you pass a customComparator.

stringCollection    .stream()    .sorted()    .filter((s) ->s.startsWith("a"))    .forEach(System.out::println);// "aaa1", "aaa2"

Keep in mind thatsorted does only create a sorted view of the stream without manipulating the ordering of the backed collection. The ordering ofstringCollection is untouched:

System.out.println(stringCollection);// ddd2, aaa2, bbb1, aaa1, bbb3, ccc, bbb2, ddd1

Map

Theintermediate operationmap converts each element into another object via the given function. The following example converts each string into an upper-cased string. But you can also usemap to transform each object into another type. The generic type of the resulting stream depends on the generic type of the function you pass tomap.

stringCollection    .stream()    .map(String::toUpperCase)    .sorted((a,b) ->b.compareTo(a))    .forEach(System.out::println);// "DDD2", "DDD1", "CCC", "BBB3", "BBB2", "AAA2", "AAA1"

Match

Various matching operations can be used to check whether a certain predicate matches the stream. All of those operations areterminal and return a boolean result.

booleananyStartsWithA =stringCollection        .stream()        .anyMatch((s) ->s.startsWith("a"));System.out.println(anyStartsWithA);// truebooleanallStartsWithA =stringCollection        .stream()        .allMatch((s) ->s.startsWith("a"));System.out.println(allStartsWithA);// falsebooleannoneStartsWithZ =stringCollection        .stream()        .noneMatch((s) ->s.startsWith("z"));System.out.println(noneStartsWithZ);// true

Count

Count is aterminal operation returning the number of elements in the stream as along.

longstartsWithB =stringCollection        .stream()        .filter((s) ->s.startsWith("b"))        .count();System.out.println(startsWithB);// 3

Reduce

Thisterminal operation performs a reduction on the elements of the stream with the given function. The result is anOptional holding the reduced value.

Optional<String>reduced =stringCollection        .stream()        .sorted()        .reduce((s1,s2) ->s1 +"#" +s2);reduced.ifPresent(System.out::println);// "aaa1#aaa2#bbb1#bbb2#bbb3#ccc#ddd1#ddd2"

Parallel Streams

As mentioned above streams can be either sequential or parallel. Operations on sequential streams are performed on a single thread while operations on parallel streams are performed concurrently on multiple threads.

The following example demonstrates how easy it is to increase the performance by using parallel streams.

First we create a large list of unique elements:

intmax =1000000;List<String>values =newArrayList<>(max);for (inti =0;i <max;i++) {UUIDuuid =UUID.randomUUID();values.add(uuid.toString());}

Now we measure the time it takes to sort a stream of this collection.

Sequential Sort

longt0 =System.nanoTime();longcount =values.stream().sorted().count();System.out.println(count);longt1 =System.nanoTime();longmillis =TimeUnit.NANOSECONDS.toMillis(t1 -t0);System.out.println(String.format("sequential sort took: %d ms",millis));// sequential sort took: 899 ms

Parallel Sort

longt0 =System.nanoTime();longcount =values.parallelStream().sorted().count();System.out.println(count);longt1 =System.nanoTime();longmillis =TimeUnit.NANOSECONDS.toMillis(t1 -t0);System.out.println(String.format("parallel sort took: %d ms",millis));// parallel sort took: 472 ms

As you can see both code snippets are almost identical but the parallel sort is roughly 50% faster. All you have to do is changestream() toparallelStream().

Maps

As already mentioned maps do not directly support streams. There's nostream() method available on theMap interface itself, however you can create specialized streams upon the keys, values or entries of a map viamap.keySet().stream(),map.values().stream() andmap.entrySet().stream().

Furthermore maps support various new and useful methods for doing common tasks.

Map<Integer,String>map =newHashMap<>();for (inti =0;i <10;i++) {map.putIfAbsent(i,"val" +i);}map.forEach((id,val) ->System.out.println(val));

The above code should be self-explaining:putIfAbsent prevents us from writing additional if null checks;forEach accepts a consumer to perform operations for each value of the map.

This example shows how to compute code on the map by utilizing functions:

map.computeIfPresent(3, (num,val) ->val +num);map.get(3);// val33map.computeIfPresent(9, (num,val) ->null);map.containsKey(9);// falsemap.computeIfAbsent(23,num ->"val" +num);map.containsKey(23);// truemap.computeIfAbsent(3,num ->"bam");map.get(3);// val33

Next, we learn how to remove entries for a given key, only if it's currently mapped to a given value:

map.remove(3,"val3");map.get(3);// val33map.remove(3,"val33");map.get(3);// null

Another helpful method:

map.getOrDefault(42,"not found");// not found

Merging entries of a map is quite easy:

map.merge(9,"val9", (value,newValue) ->value.concat(newValue));map.get(9);// val9map.merge(9,"concat", (value,newValue) ->value.concat(newValue));map.get(9);// val9concat

Merge either put the key/value into the map if no entry for the key exists, or the merging function will be called to change the existing value.

Date API

Java 8 contains a brand new date and time API under the packagejava.time. The new Date API is comparable with theJoda-Time library, however it'snot the same. The following examples cover the most important parts of this new API.

Clock

Clock provides access to the current date and time. Clocks are aware of a timezone and may be used instead ofSystem.currentTimeMillis() to retrieve the current time in milliseconds since Unix EPOCH. Such an instantaneous point on the time-line is also represented by the classInstant. Instants can be used to create legacyjava.util.Date objects.

Clockclock =Clock.systemDefaultZone();longmillis =clock.millis();Instantinstant =clock.instant();DatelegacyDate =Date.from(instant);// legacy java.util.Date

Timezones

Timezones are represented by aZoneId. They can easily be accessed via static factory methods. Timezones define the offsets which are important to convert between instants and local dates and times.

System.out.println(ZoneId.getAvailableZoneIds());// prints all available timezone idsZoneIdzone1 =ZoneId.of("Europe/Berlin");ZoneIdzone2 =ZoneId.of("Brazil/East");System.out.println(zone1.getRules());System.out.println(zone2.getRules());// ZoneRules[currentStandardOffset=+01:00]// ZoneRules[currentStandardOffset=-03:00]

LocalTime

LocalTime represents a time without a timezone, e.g. 10pm or 17:30:15. The following example creates two local times for the timezones defined above. Then we compare both times and calculate the difference in hours and minutes between both times.

LocalTimenow1 =LocalTime.now(zone1);LocalTimenow2 =LocalTime.now(zone2);System.out.println(now1.isBefore(now2));// falselonghoursBetween =ChronoUnit.HOURS.between(now1,now2);longminutesBetween =ChronoUnit.MINUTES.between(now1,now2);System.out.println(hoursBetween);// -3System.out.println(minutesBetween);// -239

LocalTime comes with various factory methods to simplify the creation of new instances, including parsing of time strings.

LocalTimelate =LocalTime.of(23,59,59);System.out.println(late);// 23:59:59DateTimeFormattergermanFormatter =DateTimeFormatter        .ofLocalizedTime(FormatStyle.SHORT)        .withLocale(Locale.GERMAN);LocalTimeleetTime =LocalTime.parse("13:37",germanFormatter);System.out.println(leetTime);// 13:37

LocalDate

LocalDate represents a distinct date, e.g. 2014-03-11. It's immutable and works exactly analog to LocalTime. The sample demonstrates how to calculate new dates by adding or subtracting days, months or years. Keep in mind that each manipulation returns a new instance.

LocalDatetoday =LocalDate.now();LocalDatetomorrow =today.plus(1,ChronoUnit.DAYS);LocalDateyesterday =tomorrow.minusDays(2);LocalDateindependenceDay =LocalDate.of(2014,Month.JULY,4);DayOfWeekdayOfWeek =independenceDay.getDayOfWeek();System.out.println(dayOfWeek);// FRIDAY

Parsing a LocalDate from a string is just as simple as parsing a LocalTime:

DateTimeFormattergermanFormatter =DateTimeFormatter        .ofLocalizedDate(FormatStyle.MEDIUM)        .withLocale(Locale.GERMAN);LocalDatexmas =LocalDate.parse("24.12.2014",germanFormatter);System.out.println(xmas);// 2014-12-24

LocalDateTime

LocalDateTime represents a date-time. It combines date and time as seen in the above sections into one instance.LocalDateTime is immutable and works similar to LocalTime and LocalDate. We can utilize methods for retrieving certain fields from a date-time:

LocalDateTimesylvester =LocalDateTime.of(2014,Month.DECEMBER,31,23,59,59);DayOfWeekdayOfWeek =sylvester.getDayOfWeek();System.out.println(dayOfWeek);// WEDNESDAYMonthmonth =sylvester.getMonth();System.out.println(month);// DECEMBERlongminuteOfDay =sylvester.getLong(ChronoField.MINUTE_OF_DAY);System.out.println(minuteOfDay);// 1439

With the additional information of a timezone it can be converted to an instant. Instants can easily be converted to legacy dates of typejava.util.Date.

Instantinstant =sylvester        .atZone(ZoneId.systemDefault())        .toInstant();DatelegacyDate =Date.from(instant);System.out.println(legacyDate);// Wed Dec 31 23:59:59 CET 2014

Formatting date-times works just like formatting dates or times. Instead of using pre-defined formats we can create formatters from custom patterns.

DateTimeFormatterformatter =DateTimeFormatter        .ofPattern("MMM dd, yyyy - HH:mm");LocalDateTimeparsed =LocalDateTime.parse("Nov 03, 2014 - 07:13",formatter);Stringstring =formatter.format(parsed);System.out.println(string);// Nov 03, 2014 - 07:13

Unlikejava.text.NumberFormat the newDateTimeFormatter is immutable andthread-safe.

For details on the pattern syntax readhere.

Annotations

Annotations in Java 8 are repeatable. Let's dive directly into an example to figure that out.

First, we define a wrapper annotation which holds an array of the actual annotations:

@interfaceHints {Hint[]value();}@Repeatable(Hints.class)@interfaceHint {Stringvalue();}

Java 8 enables us to use multiple annotations of the same type by declaring the annotation@Repeatable.

Variant 1: Using the container annotation (old school)

@Hints({@Hint("hint1"),@Hint("hint2")})classPerson {}

Variant 2: Using repeatable annotations (new school)

@Hint("hint1")@Hint("hint2")classPerson {}

Using variant 2 the java compiler implicitly sets up the@Hints annotation under the hood. That's important for reading annotation information via reflection.

Hinthint =Person.class.getAnnotation(Hint.class);System.out.println(hint);// nullHintshints1 =Person.class.getAnnotation(Hints.class);System.out.println(hints1.value().length);// 2Hint[]hints2 =Person.class.getAnnotationsByType(Hint.class);System.out.println(hints2.length);// 2

Although we never declared the@Hints annotation on thePerson class, it's still readable viagetAnnotation(Hints.class). However, the more convenient method isgetAnnotationsByType which grants direct access to all annotated@Hint annotations.

Furthermore the usage of annotations in Java 8 is expanded to two new targets:

@Target({ElementType.TYPE_PARAMETER,ElementType.TYPE_USE})@interfaceMyAnnotation {}

Where to go from here?

My programming guide to Java 8 ends here. If you want to learn more about all the new classes and features of the JDK 8 API, check out myJDK8 API Explorer. It helps you figuring out all the new classes and hidden gems of JDK 8, likeArrays.parallelSort,StampedLock andCompletableFuture - just to name a few.

I've also published a bunch of follow-up articles on myblog that might be interesting to you:

You shouldfollow me on Twitter. Thanks for reading!

About

Modern Java - A Guide to Java 8

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • Java92.1%
  • JavaScript7.9%

[8]ページ先頭

©2009-2025 Movatter.jp