Java 8 新特性

Java 8 (又称为 jdk 1.8) 是 Java 语言开发的一个主要版本。 Oracle 公司于 2014 年 3 月 18 日发布 Java 8 ,它支持函数式编程,新的 JavaScript 引擎,新的日期 API,新的Stream API 等。

新特性

Java8 新增了非常多的特性,我们主要讨论以下几个:

  • Lambda 表达式

    Lambda允许把函数作为一个方法的参数(函数作为参数传递进方法中。

  • 方法引用

    方法引用提供了非常有用的语法,可以直接引用已有Java类或对象(实例)的方法或构造器。与lambda联合使用,方法引用可以使语言的构造更紧凑简洁,减少冗余代码。

  • 默认方法

    默认方法就是一个在接口里面有了一个实现的方法。

    代码示例:

    https://github.com/java-8/java8-impatient/tree/master/src/main/java/study/java8/trait

  /**
 * InterfaceWithDefaultMethod.java
 */
package study.java8.trait;

/**
 * 
 * @author jack 2016年8月10日 下午3:51:19
 */
public interface InterfaceWithDefaultMethod {

    abstract public void abstractMethod();

    public static void staticMethod() {
        System.out.println("staticMethod  print");
    }

    public default void defaultMethod() {
        System.out.println("defaultMethod  print");
    }

    public static void main(String[] args) {// 接口可以有main函数
        staticMethod();

        // InterfaceWithDefaultMethod iMethod = new
        // InterfaceWithDefaultMethod(); 接口不能new实例化
        // defaultMethod();
    }

}
  /**
 * InterfaceWithDefaultMethodImpl.java
 */
package study.java8.trait;

/**
 * @author jack 2016年8月10日 下午3:57:06
 */
public class InterfaceWithDefaultMethodImpl implements InterfaceWithDefaultMethod {

    public static void main(String[] args) {
        InterfaceWithDefaultMethodImpl impl = new InterfaceWithDefaultMethodImpl();
        impl.defaultMethod();
        impl.abstractMethod();
        // impl.staticMethod(); // 调不到接口里面的静态方法, The method staticMethod() is
        // undefined for the type InterfaceWithDefaultMethodImpl
        InterfaceWithDefaultMethod.staticMethod();// 类似scala里面的object的意思
    }

    /*
     * (non-Javadoc)
     * 
     * @see study.java8.trait.InterfaceWithDefaultMethod#abstractMethod()
     */
    @Override
    public void abstractMethod() {
        // Do Something ...
        System.out.println("Do Something ...");

    }

}
  /**
 * StreamApiDemo.java
 */
package study.java8.stream;

import java.util.List;
import java.util.stream.Stream;
import java.util.ArrayList;

/**
 * @author jack 2016年8月16日 下午4:48:22
 */
public class StreamApiDemo {

    /**
     * @param args
     */
    public static void main(String[] args) {

        List<String> fpList = new ArrayList<>();
        fpList.add("Scala");
        fpList.add("Haskell");
        fpList.add("Clojure");
        fpList.add("Lisp");

        System.out.println("=====原来的list=========");

        fpList.forEach(System.out::println);

        System.out.println("======排序输出========");

        fpList.stream()
              .sorted()
              .forEach(System.out::println);

        System.out.println("=====Stream的排序不影响原来list=========");

        fpList.forEach(System.out::println);

        Stream<String> stream = fpList.stream()
                                      .sorted();

        System.out.println("==============");

        fpList.stream()
              .sorted()
              .filter((s) -> s.contains("S") || s.contains("s"))
              .forEach(System.out::println);

    }

}

并发Stream

/**
 * ParallelStreamDemo.java
 */
package study.java8.stream;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author jack 2016年8月16日 下午5:23:51
 */
public class ParallelStreamDemo {

    /**
     * @param args
     */
    public static void main(String[] args) {
        int max = 1000000;
        List<String> values = new ArrayList<>(max);
        for (int i = 0; i < max; i++) {
            UUID uuid = UUID.randomUUID();
            values.add(uuid.toString());
        }

        long st0 = System.nanoTime();

        long scount = values.stream()
                            .sorted()
                            .count();
        System.out.println(scount);

        long st1 = System.nanoTime();

        long smillis = TimeUnit.NANOSECONDS.toMillis(st1 - st0);
        System.out.println(String.format("sequential sort took: %d ms",
                                         smillis));

        long pt0 = System.nanoTime();

        long pcount = values.parallelStream()
                            .sorted()
                            .count();
        System.out.println(pcount);

        long pt1 = System.nanoTime();

        long pmillis = TimeUnit.NANOSECONDS.toMillis(pt1 - pt0);
        System.out.println(String.format("parallel sort took: %d ms",
                                         pmillis));

    }

}
  • Date Time API

    加强对日期与时间的处理。

代码示例: https://github.com/java-8/java8-impatient/blob/master/src/main/java/study/java8/time/LocalTime.java


/**
 * LocalTime.java
 */
package study.java8.time;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author jack 2016年8月15日 上午10:19:38
 */
public class LocalTime {

    /**
     * @param args
     */
    public static void main(String[] args) {
        LocalDate date = LocalDate.now();
        String ds = date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        System.out.println(ds);

        LocalDateTime ldt = LocalDateTime.now();
        System.out.println(ldt.getHour());
        System.out.println(ldt.getMinute());
        System.out.println(ldt.getSecond());

        String dst = ldt.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        System.out.println(dst);

    }

}
  • Optional 类

    Optional 类已经成为 Java 8 类库的一部分,用来解决空指针异常。

  • Nashorn, JavaScript 引擎

    Java 8提供了一个新的Nashorn javascript引擎,它允许我们在JVM上运行特定的javascript应用。

更多的新特性可以参阅官网:What's New in JDK 8

results matching ""

    No results matching ""