Java8新特性

Java8新特性

文章目录

  • Java8新特性
    • 一、概述
      • [Java Programming Language:](http://docs.oracle.com/javase/8/docs/technotes/guides/language/enhancements.html#javase8)
      • Collections
    • 二、 [lambda表达式(Lambda Expressions)](https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html)&[方法引用(Method references)](https://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html)
      • 2.1 什么是lambda
      • 2.2 lambda的语法
      • 2.3 什么是方法引用
    • 三、 [默认方法(Default methods)](https://docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.html)
    • 四、 [重复注释(Repeating Annotations)](https://docs.oracle.com/javase/tutorial/java/annotations/repeating.html)
    • 五、 [类型注释(Type Annotations)](https://docs.oracle.com/javase/tutorial/java/annotations/type_annotations.html)
    • 六、 [优化类型推断(Improved type inference)](https://docs.oracle.com/javase/tutorial/java/generics/genTypeInference.html)
    • 七、 [反射获取方法参数(Method parameter reflection)](https://docs.oracle.com/javase/tutorial/reflect/member/methodparameterreflection.html)
    • 八、 [stream api](https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html)
    • 九、 [hashmap的优化](https://openjdk.org/jeps/180)

一、概述

Java Programming Language:

  • Lambda Expressions, a new language feature, has been introduced in this release. They enable you to treat functionality as a method argument, or code as data. Lambda expressions let you express instances of single-method interfaces (referred to as functional interfaces) more compactly.
  • Method references provide easy-to-read lambda expressions for methods that already have a name.
  • Default methods enable new functionality to be added to the interfaces of libraries and ensure binary compatibility with code written for older versions of those interfaces.
  • Repeating Annotations provide the ability to apply the same annotation type more than once to the same declaration or type use.
  • Type Annotations provide the ability to apply an annotation anywhere a type is used, not just on a declaration. Used with a pluggable type system, this feature enables improved type checking of your code.
  • Improved type inference.
  • Method parameter reflection.

Collections

  • Classes in the new java.util.stream package provide a Stream API to support functional-style operations on streams of elements. The Stream API is integrated into the Collections API, which enables bulk operations on collections, such as sequential or parallel map-reduce transformations.
  • Performance Improvement for HashMaps with Key Collisions

简单翻译如下:

java特性:

​ lambda表达式(Lambda Expressions)

​ 方法引用(Method references)

​ 默认方法(Default methods)

​ 重复注释(Repeating Annotations)

​ 类型注释(Type Annotations)

​ 优化类型推断(Improved type inference)

​ 反射获取方法参数(Method parameter reflection)

集合:

​ 添加stream api

​ hashmap的优化

二、 lambda表达式(Lambda Expressions)&方法引用(Method references)

2.1 什么是lambda

类似匿名函数,可以将方法作为参数进行传递

2.2 lambda的语法

(方法参数) -> {方法体}

public class Test {
  public static void main(String[] args) {
    IAdd ic = (int i) -> {
      return i + 3;
    };
    System.out.println( ic.add(1));
    
    ISubtraction is = (int i, int j) -> {
      return i - j;
    };
    System.out.println(is.subtraction(5, 2));
  }
}

interface IAdd {
  int add(int i);
}

interface ISubtraction {
    int subtraction(int i, int j);
}

上述lambda部分也可以简写成

IAdd ic = i -> i + 3;

ISubtraction is = (i, j) -> i - j;

2.3 什么是方法引用

通过对象::方法名的方式使用方法

public class Test {
  public static void main(String[] args) {
    AddCalc ac = new AddCalc();
    IAdd ia = ac::increment;
    System.out.println(ia.add(4));  
  }
}

class AddCalc {
    public int increment(int i) {
        return i + 1;
    }
}

interface IAdd {
    int add(int i);
}

三、 默认方法(Default methods)

interface It {
    default void print() {
        System.out.println("this is a default method...");
    }
    
    static void staticPrint() {
        System.out.println("this is a static method...");
    }
}

四、 重复注释(Repeating Annotations)

@Schedule(dayOfMonth="last")
@Schedule(dayOfWeek="Fri", hour="23")
public void doPeriodicCleanup() { ... }

// In order for the compiler to do this, two declarations are required in your code.
// Step 1: Declare a Repeatable Annotation Type
import java.lang.annotation.Repeatable;

@Repeatable(Schedules.class)
public @interface Schedule {
  String dayOfMonth() default "first";
  String dayOfWeek() default "Mon";
  int hour() default 12;
}

// Step 2: Declare the Containing Annotation Type
public @interface Schedules { 
    Schedule[] value(); 
}

五、 类型注释(Type Annotations)

在Java8之前,注解只能在声明的地方用。Java8开始,注解也可以用于任何类型的使用。

@NonNull String str;
new @NotEmpty List<String>;

六、 优化类型推断(Improved type inference)

static <T> T pick(T a1, T a2) { return a2; }
Serializable s = pick("d", new ArrayList<String>());

调用pick方法的时候,推理确定传递的第二个参数是Serializable类型

七、 反射获取方法参数(Method parameter reflection)

Java8添加了Parameter类,To store formal parameter names in a particular .class file, and thus enable the Reflection API to retrieve formal parameter names, compile the source file with the -parameters option to the javac compiler.

import java.lang.reflect.*;
import java.util.function.*;
import static java.lang.System.out;
 
public class MethodParameterSpy {
     
    private static final String  fmt = "%24s: %s%n";
 
    // for the morbidly curious
    <E extends RuntimeException> void genericThrow() throws E {}
     
    public static void printClassConstructors(Class c) {
        Constructor[] allConstructors = c.getConstructors();
        out.format(fmt, "Number of constructors", allConstructors.length);
        for (Constructor currentConstructor : allConstructors) {
            printConstructor(currentConstructor);
        }  
        Constructor[] allDeclConst = c.getDeclaredConstructors();
        out.format(fmt, "Number of declared constructors",
            allDeclConst.length);
        for (Constructor currentDeclConst : allDeclConst) {
            printConstructor(currentDeclConst);
        }          
    }
     
    public static void printClassMethods(Class c) {
       Method[] allMethods = c.getDeclaredMethods();
        out.format(fmt, "Number of methods", allMethods.length);
        for (Method m : allMethods) {
            printMethod(m);
        }        
    }
     
    public static void printConstructor(Constructor c) {
        out.format("%s%n", c.toGenericString());
        Parameter[] params = c.getParameters();
        out.format(fmt, "Number of parameters", params.length);
        for (int i = 0; i < params.length; i++) {
            printParameter(params[i]);
        }
    }
     
    public static void printMethod(Method m) {
        out.format("%s%n", m.toGenericString());
        out.format(fmt, "Return type", m.getReturnType());
        out.format(fmt, "Generic return type", m.getGenericReturnType());
                 
        Parameter[] params = m.getParameters();
        for (int i = 0; i < params.length; i++) {
            printParameter(params[i]);
        }
    }
     
    public static void printParameter(Parameter p) {
        out.format(fmt, "Parameter class", p.getType());
        out.format(fmt, "Parameter name", p.getName());
        out.format(fmt, "Modifiers", p.getModifiers());
        out.format(fmt, "Is implicit?", p.isImplicit());
        out.format(fmt, "Is name present?", p.isNamePresent());
        out.format(fmt, "Is synthetic?", p.isSynthetic());
    }
     
    public static void main(String... args) {        
 
        try {
            printClassConstructors(Class.forName(args[0]));
            printClassMethods(Class.forName(args[0]));
        } catch (ClassNotFoundException x) {
            x.printStackTrace();
        }
    }
}

八、 stream api

Streams can be obtained in a number of ways. Some examples include:

  • From a Collection via the stream() and parallelStream() methods;
  • From an array via Arrays.stream(Object[\]);
  • From static factory methods on the stream classes, such as Stream.of(Object[\]), IntStream.range(int, int) or Stream.iterate(Object, UnaryOperator);
  • The lines of a file can be obtained from BufferedReader.lines();
  • Streams of file paths can be obtained from methods in Files;
  • Streams of random numbers can be obtained from Random.ints();
  • Numerous other stream-bearing methods in the JDK, including BitSet.stream(), Pattern.splitAsStream(java.lang.CharSequence), and JarFile.stream().
List<String> l = new ArrayList(Arrays.asList("one", "two"));
Stream<String> sl = l.stream();
l.add("three");
String s = sl.collect(joining(" "));
l.stream().forEach(e -> System.out.printf("forEach: %s", e));
System.out.printf("\ns: %s", s);

// forEach: oneforEach: twoforEach: three
// s: one two three

九、 hashmap的优化

1、引入红黑树

2、优化hash的实现

你可能感兴趣的:(java,java)