Java8新特性

Java8新特性

一、概述

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:

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的实现

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值