Home >Java >javaTutorial >Detailed explanation of the top ten new features of JAVA8
"Java is still not dead—and people are starting to figure that out."
This tutorial will use simple annotated code to describe new features, and you won't see large blocks of scary text.
1. Default method of interface
Java 8 allows us to add a non-abstract method implementation to the interface. We only need to use the default keyword. This feature is also called an extension method. The example is as follows :
interface Formula { double calculate(int a); default double sqrt(int a) { return Math.sqrt(a); } }
The Formula interface also defines the sqrt method in addition to the calculate method. Subclasses that implement the Formula interface only need to implement a calculate method. The default method sqrt will be used directly on the subclass.
Formula formula = new Formula() { @Override public double calculate(int a) { return sqrt(a * 100); } }; formula.calculate(100); // 100.0 formula.sqrt(16); // 4.0
The formula in the article is implemented as an instance of an anonymous class. The code is very easy to understand. The calculation of sqrt(a * 100) is implemented in 6 lines of code. In the next section, we'll see a simpler way of implementing a single-method interface.
Translator's Note: There is only single inheritance in Java. If you want to give a class new characteristics, it is usually implemented using an interface. Multiple inheritance is supported in C++, allowing a subclass to have multiple parents at the same time. Interfaces and functions of classes. In other languages, the method of allowing a class to have other reusable codes at the same time is called mixin. This feature of the new Java 8 is closer to the Scala trait from the perspective of compiler implementation. There is also a concept called extension method in C#, which allows extension methods to existing types. This is semantically different from Java 8.
2. Lambda expression
First look at how strings are arranged in old versions of Java:
Listf7e83be87db5cd2d9a8a0b8117b38cd4 names = Arrays.asList("peter", "anna", "mike", "xenia"); Collections.sort(names, new Comparatorf7e83be87db5cd2d9a8a0b8117b38cd4() { @Override public int compare(String a, String b) { return b.compareTo(a); } });
Just pass in the static method Collections.sort A List object and a comparator to sort the items in the specified order. The usual approach is to create an anonymous comparator object and pass it to the sort method.
In Java 8 you no longer need to use this traditional anonymous object method. Java 8 provides a more concise syntax, lambda expression:
Collections.sort(names, (String a, String b) -> { return b.compareTo(a); });
See it, the code Become more segmented and more readable, but it can actually be written shorter:
Collections.sort(names, (String a, String b) -> b.compareTo(a));
For function bodies with only one line of code, you can remove the curly brackets {} and the return keyword, but you You can also write it shorter:
Collections.sort(names, (a, b) -> b.compareTo(a));
The Java compiler can automatically deduce the parameter type, so you don’t have to write the type again. Next, let’s see what more convenient things lambda expressions can make:
3. Functional interface
How are Lambda expressions expressed in the Java type system? Each lambda expression corresponds to a type, usually an interface type. "Functional interface" refers to an interface that only contains one abstract method. Every lambda expression of this type will be matched to this abstract method. Because default methods are not considered abstract methods, you can also add default methods to your functional interface.
We can treat lambda expressions as any interface type that contains only one abstract method. To ensure that your interface must meet this requirement, you only need to add @FunctionalInterface annotation, the compiler will report an error if it finds that the interface you annotated with this annotation has more than one abstract method.
The example is as follows:
@FunctionalInterface interface Converter9efde64c8e78ec8daba603d9ac61febe { T convert(F from); } Converter4c67ceab372661f5825b546aa977ae81 converter = (from) -> Integer.valueOf(from); Integer converted = converter.convert("123"); System.out.println(converted); // 123
It should be noted that if @FunctionalInterface is not specified, the above code is also correct.
Translator's Note: Mapping lambda expressions to a single-method interface was implemented in other languages before Java 8, such as the Rhino JavaScript interpreter. , if a function parameter receives a single-method interface and you pass it a function, the Rhino interpreter will automatically create an adapter from a single-interface instance to the function. Typical application scenarios include org.w3c.dom.events.EventTarget. The second parameter of addEventListener is EventListener.
4. Method and constructor references
The code in the previous section can also be represented by static method references:
Converter4c67ceab372661f5825b546aa977ae81 converter = Integer::valueOf; Integer converted = converter.convert("123"); System.out.println(converted); // 123
Java 8 allows you to use the :: keyword To pass a method or constructor reference, the above code shows how to reference a static method. We can also reference an object's method:
converter = something::startsWith; String converted = converter.convert("Java"); System.out.println(converted); // "J"
Next, let's see how the constructor is referenced using the :: keyword , first we define a simple class containing multiple constructors:
class Person { String firstName; String lastName; Person() {} Person(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } }
Next we specify an object factory interface used to create Person objects:
interface PersonFactory8a91318cb06ddca0a406341b559597e2 { P create(String firstName, String lastName); }
Here we use constructor references To associate them instead of implementing a complete factory:
PersonFactory8abf60ac54173a2785e603c7a1f95b4e personFactory = Person::new; Person person = personFactory.create("Peter", "Parker");
We only need to use Person::new to get a reference to the Person class constructor, and the Java compiler will automatically follow the signature of the PersonFactory.create method to choose the appropriate constructor.
5. Lambda Scope
The way to access the outer scope in a lambda expression is very similar to that in the old version of anonymous objects. You can directly access outer local variables marked final, or instance fields and static variables.
6. Access local variables
We can directly access the outer local variables in lambda expressions:
final int num = 1; Converter4a74c80eaab3e4028fdc76296099a1bc stringConverter = (from) -> String.valueOf(from + num); stringConverter.convert(2); // 3
But unlike anonymous objects, the variables here num does not need to be declared as final, the code is also correct:
int num = 1; Converter4a74c80eaab3e4028fdc76296099a1bc stringConverter = (from) -> String.valueOf(from + num); stringConverter.convert(2); // 3
However, the num here must not be modified by subsequent code (that is, it has implicit final semantics). For example, the following cannot be compiled:
int num = 1; Converter4a74c80eaab3e4028fdc76296099a1bc stringConverter = (from) -> String.valueOf(from + num); num = 3;
在lambda表达式中试图修改num同样是不允许的。
七、访问对象字段与静态变量
和本地变量不同的是,lambda内部对于实例的字段以及静态变量是即可读又可写。该行为和匿名对象是一致的:
class Lambda4 { static int outerStaticNum; int outerNum; void testScopes() { Converter4a74c80eaab3e4028fdc76296099a1bc stringConverter1 = (from) -> { outerNum = 23; return String.valueOf(from); }; Converter4a74c80eaab3e4028fdc76296099a1bc stringConverter2 = (from) -> { outerStaticNum = 72; return String.valueOf(from); }; } }
八、访问接口的默认方法
还记得第一节中的formula例子么,接口Formula定义了一个默认方法sqrt可以直接被formula的实例包括匿名对象访问到,但是在lambda表达式中这个是不行的。
Lambda表达式中是无法访问到默认方法的,以下代码将无法编译:
Formula formula = (a) -> sqrt( a * 100); Built-in Functional Interfaces
JDK 1.8 API包含了很多内建的函数式接口,在老Java中常用到的比如Comparator或者Runnable接口,这些接口都增加了@FunctionalInterface注解以便能用在lambda上。
Java 8 API同样还提供了很多全新的函数式接口来让工作更加方便,有一些接口是来自Google Guava库里的,即便你对这些很熟悉了,还是有必要看看这些是如何扩展到lambda上使用的。
Predicate接口
Predicate 接口只有一个参数,返回boolean类型。该接口包含多种默认方法来将Predicate组合成其他复杂的逻辑(比如:与,或,非):
Predicatef7e83be87db5cd2d9a8a0b8117b38cd4 predicate = (s) -> s.length() > 0; predicate.test("foo"); // true predicate.negate().test("foo"); // false Predicate558d764cdd41f624c4c5c9c8da137eab nonNull = Objects::nonNull; Predicate558d764cdd41f624c4c5c9c8da137eab isNull = Objects::isNull; Predicatef7e83be87db5cd2d9a8a0b8117b38cd4 isEmpty = String::isEmpty; Predicatef7e83be87db5cd2d9a8a0b8117b38cd4 isNotEmpty = isEmpty.negate();
Function 接口
Function 接口有一个参数并且返回一个结果,并附带了一些可以和其他函数组合的默认方法(compose, andThen):
Function4c67ceab372661f5825b546aa977ae81 toInteger = Integer::valueOf; Function18fed3eaa375b9cabd6da695ec776cac backToString = toInteger.andThen(String::valueOf); backToString.apply("123"); // "123"
Supplier 接口
Supplier 接口返回一个任意范型的值,和Function接口不同的是该接口没有任何参数
Supplier8abf60ac54173a2785e603c7a1f95b4e personSupplier = Person::new; personSupplier.get(); // new Person
Consumer 接口
Consumer 接口表示执行在单个参数上的操作。
Consumer8abf60ac54173a2785e603c7a1f95b4e greeter = (p) -> System.out.println("Hello, " + p.firstName); greeter.accept(new Person("Luke", "Skywalker"));
Comparator 接口
Comparator 是老Java中的经典接口, Java 8在此之上添加了多种默认方法:
Comparator8abf60ac54173a2785e603c7a1f95b4e comparator = (p1, p2) -> p1.firstName.compareTo(p2.firstName); Person p1 = new Person("John", "Doe"); Person p2 = new Person("Alice", "Wonderland"); comparator.compare(p1, p2); // > 0 comparator.reversed().compare(p1, p2); // < 0
Optional 接口
Optional 不是函数是接口,这是个用来防止NullPointerException异常的辅助类型,这是下一届中将要用到的重要概念,现在先简单的看看这个接口能干什么:
Optional 被定义为一个简单的容器,其值可能是null或者不是null。在Java 8之前一般某个函数应该返回非空对象但是偶尔却可能返回了null,而在Java 8中,不推荐你返回null而是返回Optional。
Optionalf7e83be87db5cd2d9a8a0b8117b38cd4 optional = Optional.of("bam"); optional.isPresent(); // true optional.get(); // "bam" optional.orElse("fallback"); // "bam" optional.ifPresent((s) -> System.out.println(s.charAt(0))); // "b"
Stream 接口
java.util.Stream 表示能应用在一组元素上一次执行的操作序列。Stream 操作分为中间操作或者最终操作两种,最终操作返回一特定类型的计算结果,而中间操作返回Stream本身,这样你就可以将多个操作依次串起来。Stream 的创建需要指定一个数据源,比如 java.util.Collection的子类,List或者Set, Map不支持。Stream的操作可以串行执行或者并行执行。
首先看看Stream是怎么用,首先创建实例代码的用到的数据List:
Listf7e83be87db5cd2d9a8a0b8117b38cd4 stringCollection = new ArrayLista8093152e673feb7aba1828c43532094(); stringCollection.add("ddd2"); stringCollection.add("aaa2"); stringCollection.add("bbb1"); stringCollection.add("aaa1"); stringCollection.add("bbb3"); stringCollection.add("ccc"); stringCollection.add("bbb2"); stringCollection.add("ddd1");
Java 8扩展了集合类,可以通过 Collection.stream() 或者 Collection.parallelStream() 来创建一个Stream。下面几节将详细解释常用的Stream操作:
Filter 过滤
过滤通过一个predicate接口来过滤并只保留符合条件的元素,该操作属于中间操作,所以我们可以在过滤后的结果来应用其他Stream操作(比如forEach)。forEach需要一个函数来对过滤后的元素依次执行。forEach是一个最终操作,所以我们不能在forEach之后来执行其他Stream操作。
stringCollection .stream() .filter((s) -> s.startsWith("a")) .forEach(System.out::println); // "aaa2", "aaa1"
Sort 排序
排序是一个中间操作,返回的是排序好后的Stream。如果你不指定一个自定义的Comparator则会使用默认排序。
stringCollection .stream() .sorted() .filter((s) -> s.startsWith("a")) .forEach(System.out::println); // "aaa1", "aaa2"
需要注意的是,排序只创建了一个排列好后的Stream,而不会影响原有的数据源,排序之后原数据stringCollection是不会被修改的:
System.out.println(stringCollection); // ddd2, aaa2, bbb1, aaa1, bbb3, ccc, bbb2, ddd1
Map 映射
中间操作map会将元素根据指定的Function接口来依次将元素转成另外的对象,下面的示例展示了将字符串转换为大写字符串。你也可以通过map来讲对象转换成其他类型,map返回的Stream类型是根据你map传递进去的函数的返回值决定的。
stringCollection .stream() .map(String::toUpperCase) .sorted((a, b) -> b.compareTo(a)) .forEach(System.out::println); // "DDD2", "DDD1", "CCC", "BBB3", "BBB2", "AAA2", "AAA1"Match 匹配
Stream提供了多种匹配操作,允许检测指定的Predicate是否匹配整个Stream。所有的匹配操作都是最终操作,并返回一个boolean类型的值。
boolean anyStartsWithA = stringCollection .stream() .anyMatch((s) -> s.startsWith("a")); System.out.println(anyStartsWithA); // true boolean allStartsWithA = stringCollection .stream() .allMatch((s) -> s.startsWith("a")); System.out.println(allStartsWithA); // false boolean noneStartsWithZ = stringCollection .stream() .noneMatch((s) -> s.startsWith("z")); System.out.println(noneStartsWithZ); // true
Count 计数
计数是一个最终操作,返回Stream中元素的个数,返回值类型是long。
long startsWithB = stringCollection .stream() .filter((s) -> s.startsWith("b")) .count(); System.out.println(startsWithB); // 3
Reduce 规约
这是一个最终操作,允许通过指定的函数来讲stream中的多个元素规约为一个元素,规越后的结果是通过Optional接口表示的:
Optional<String> reduced = stringCollection .stream() .sorted() .reduce((s1, s2) -> s1 + "#" + s2); reduced.ifPresent(System.out::println); // "aaa1#aaa2#bbb1#bbb2#bbb3#ccc#ddd1#ddd2"
并行Streams
前面提到过Stream有串行和并行两种,串行Stream上的操作是在一个线程中依次完成,而并行Stream则是在多个线程上同时执行。
下面的例子展示了是如何通过并行Stream来提升性能:
首先我们创建一个没有重复元素的大表:
int max = 1000000; List<String> values = new ArrayList<>(max); for (int i = 0; i < max; i++) { UUID uuid = UUID.randomUUID(); values.add(uuid.toString()); }
然后我们计算一下排序这个Stream要耗时多久,
串行排序:
long t0 = System.nanoTime(); long count = values.stream().sorted().count(); System.out.println(count); long t1 = System.nanoTime(); long millis = TimeUnit.NANOSECONDS.toMillis(t1 - t0); System.out.println(String.format("sequential sort took: %d ms", millis));
// 串行耗时: 899 ms
并行排序:
long t0 = System.nanoTime(); long count = values.parallelStream().sorted().count(); System.out.println(count); long t1 = System.nanoTime(); long millis = TimeUnit.NANOSECONDS.toMillis(t1 - t0); System.out.println(String.format("parallel sort took: %d ms", millis));
// 并行排序耗时: 472 ms
上面两个代码几乎是一样的,但是并行版的快了50%之多,唯一需要做的改动就是将stream()改为parallelStream()。
Map
前面提到过,Map类型不支持stream,不过Map提供了一些新的有用的方法来处理一些日常任务。
Map<Integer, String> map = new HashMap<>(); for (int i = 0; i < 10; i++) { map.putIfAbsent(i, "val" + i); }
map.forEach((id, val) -> System.out.println(val));
以上代码很容易理解, putIfAbsent 不需要我们做额外的存在性检查,而forEach则接收一个Consumer接口来对map里的每一个键值对进行操作。
下面的例子展示了map上的其他有用的函数:
map.computeIfPresent(3, (num, val) -> val + num); map.get(3); // val33 map.computeIfPresent(9, (num, val) -> null); map.containsKey(9); // false map.computeIfAbsent(23, num -> "val" + num); map.containsKey(23); // true map.computeIfAbsent(3, num -> "bam"); map.get(3); // val33
接下来展示如何在Map里删除一个键值全都匹配的项:
map.remove(3, "val3"); map.get(3); // val33 map.remove(3, "val33"); map.get(3); // null
另外一个有用的方法:
map.getOrDefault(42, "not found"); // not found
对Map的元素做合并也变得很容易了:
map.merge(9, "val9", (value, newValue) -> value.concat(newValue)); map.get(9); // val9 map.merge(9, "concat", (value, newValue) -> value.concat(newValue)); map.get(9); // val9concat
Merge做的事情是如果键名不存在则插入,否则则对原键对应的值做合并操作并重新插入到map中。
九、Date API
Java 8 在包java.time下包含了一组全新的时间日期API。新的日期API和开源的Joda-Time库差不多,但又不完全一样,下面的例子展示了这组新API里最重要的一些部分:
Clock 时钟
Clock类提供了访问当前日期和时间的方法,Clock是时区敏感的,可以用来取代 System.currentTimeMillis() 来获取当前的微秒数。某一个特定的时间点也可以使用Instant类来表示,Instant类也可以用来创建老的java.util.Date对象。
Clock clock = Clock.systemDefaultZone(); long millis = clock.millis(); Instant instant = clock.instant(); Date legacyDate = Date.from(instant); // legacy java.util.Date
Timezones 时区
在新API中时区使用ZoneId来表示。时区可以很方便的使用静态方法of来获取到。 时区定义了到UTS时间的时间差,在Instant时间点对象到本地日期对象之间转换的时候是极其重要的。
System.out.println(ZoneId.getAvailableZoneIds()); // prints all available timezone ids ZoneId zone1 = ZoneId.of("Europe/Berlin"); ZoneId zone2 = ZoneId.of("Brazil/East"); System.out.println(zone1.getRules()); System.out.println(zone2.getRules()); // ZoneRules[currentStandardOffset=+01:00] // ZoneRules[currentStandardOffset=-03:00]
LocalTime 本地时间
LocalTime 定义了一个没有时区信息的时间,例如 晚上10点,或者 17:30:15。下面的例子使用前面代码创建的时区创建了两个本地时间。之后比较时间并以小时和分钟为单位计算两个时间的时间差:
LocalTime now1 = LocalTime.now(zone1); LocalTime now2 = LocalTime.now(zone2); System.out.println(now1.isBefore(now2)); // false long hoursBetween = ChronoUnit.HOURS.between(now1, now2); long minutesBetween = ChronoUnit.MINUTES.between(now1, now2); System.out.println(hoursBetween); // -3 System.out.println(minutesBetween); // -239
LocalTime 提供了多种工厂方法来简化对象的创建,包括解析时间字符串。
LocalTime late = LocalTime.of(23, 59, 59); System.out.println(late); // 23:59:59 DateTimeFormatter germanFormatter = DateTimeFormatter .ofLocalizedTime(FormatStyle.SHORT) .withLocale(Locale.GERMAN); LocalTime leetTime = LocalTime.parse("13:37", germanFormatter); System.out.println(leetTime); // 13:37
LocalDate 本地日期
LocalDate 表示了一个确切的日期,比如 2014-03-11。该对象值是不可变的,用起来和LocalTime基本一致。下面的例子展示了如何给Date对象加减天/月/年。另外要注意的是这些对象是不可变的,操作返回的总是一个新实例。
LocalDate today = LocalDate.now(); LocalDate tomorrow = today.plus(1, ChronoUnit.DAYS); LocalDate yesterday = tomorrow.minusDays(2); LocalDate independenceDay = LocalDate.of(2014, Month.JULY, 4); DayOfWeek dayOfWeek = independenceDay.getDayOfWeek();
System.out.println(dayOfWeek); // FRIDAY
从字符串解析一个LocalDate类型和解析LocalTime一样简单:
DateTimeFormatter germanFormatter = DateTimeFormatter .ofLocalizedDate(FormatStyle.MEDIUM) .withLocale(Locale.GERMAN); LocalDate xmas = LocalDate.parse("24.12.2014", germanFormatter); System.out.println(xmas); // 2014-12-24
LocalDateTime 本地日期时间
LocalDateTime 同时表示了时间和日期,相当于前两节内容合并到一个对象上了。LocalDateTime和LocalTime还有LocalDate一样,都是不可变的。LocalDateTime提供了一些能访问具体字段的方法。
LocalDateTime sylvester = LocalDateTime.of(2014, Month.DECEMBER, 31, 23, 59, 59); DayOfWeek dayOfWeek = sylvester.getDayOfWeek(); System.out.println(dayOfWeek); // WEDNESDAY Month month = sylvester.getMonth(); System.out.println(month); // DECEMBER long minuteOfDay = sylvester.getLong(ChronoField.MINUTE_OF_DAY); System.out.println(minuteOfDay); // 1439
只要附加上时区信息,就可以将其转换为一个时间点Instant对象,Instant时间点对象可以很容易的转换为老式的java.util.Date。
Instant instant = sylvester .atZone(ZoneId.systemDefault()) .toInstant(); Date legacyDate = Date.from(instant); System.out.println(legacyDate); // Wed Dec 31 23:59:59 CET 2014
格式化LocalDateTime和格式化时间和日期一样的,除了使用预定义好的格式外,我们也可以自己定义格式:
DateTimeFormatter formatter = DateTimeFormatter .ofPattern("MMM dd, yyyy - HH:mm"); LocalDateTime parsed = LocalDateTime.parse("Nov 03, 2014 - 07:13", formatter); String string = formatter.format(parsed); System.out.println(string); // Nov 03, 2014 - 07:13
和java.text.NumberFormat不一样的是新版的DateTimeFormatter是不可变的,所以它是线程安全的。
关于时间日期格式的详细信息:http://download.java.net/jdk8/docs/api/java/time/format/DateTimeFormatter.html
十、Annotation 注解
在Java 8中支持多重注解了,先看个例子来理解一下是什么意思。
首先定义一个包装类Hints注解用来放置一组具体的Hint注解:
@interface Hints { Hint[] value(); } @Repeatable(Hints.class) @interface Hint { String value(); }
Java 8允许我们把同一个类型的注解使用多次,只需要给该注解标注一下@Repeatable即可。
例 1: 使用包装类当容器来存多个注解(老方法)
@Hints({@Hint("hint1"), @Hint("hint2")}) class Person {}
例 2:使用多重注解(新方法)
@Hint("hint1") @Hint("hint2") class Person {}
第二个例子里java编译器会隐性的帮你定义好@Hints注解,了解这一点有助于你用反射来获取这些信息:
Hint hint = Person.class.getAnnotation(Hint.class); System.out.println(hint); // null Hints hints1 = Person.class.getAnnotation(Hints.class); System.out.println(hints1.value().length); // 2 Hint[] hints2 = Person.class.getAnnotationsByType(Hint.class); System.out.println(hints2.length); // 2
即便我们没有在Person类上定义@Hints注解,我们还是可以通过 getAnnotation(Hints.class) 来获取 @Hints注解,更加方便的方法是使用 getAnnotationsByType 可以直接获取到所有的@Hint注解。
另外Java 8的注解还增加到两种新的target上了:
@Target({ElementType.TYPE_PARAMETER, ElementType.TYPE_USE}) @interface MyAnnotation {}
关于Java 8的新特性就写到这了,肯定还有更多的特性等待发掘。JDK 1.8里还有很多很有用的东西,比如Arrays.parallelSort, StampedLock和CompletableFuture等等。
更多JAVA8 十大新特性详解相关文章请关注PHP中文网!