JDK1.8新特性(一)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/J080624/article/details/84976155

【1】底层数据结构改变

jdk1.8 中对集合的底层结构做了调整。

如HashMap从1.7的数据+链表的形式调整为数据+链表+红黑树。

ConcurrentHashMap从分段机制+数组+链表+红黑树到CAS+数组+链表+红黑树。

这里先简要记录,后续会详解Map的原理与区别。

【2】JVM内存调整

jdk1.8中去掉了方法去(永久代),使用元空间(MetaSpace)代替,后者使用直接内存(物理内存)。

参考博文:JVM内存模型详解


【3】Lambda表达式

① 定义

Lambda 是一个匿名函数,我们可以把Lambda 表达式理解为是一段可以传递的代码(将代码像数据一样进行传递)。可以写出更简洁、更灵活的代码。作为一种更紧凑的代码风格,使Java的语言表达能力得到了提升。

Lambda 表达式在Java 语言中引入了一个新的语法元素和操作符。这个操作符为“->” ,该操作符被称为Lambda 操作符或剪头操作符。它将Lambda 分为两个部分:

  • 左侧:指定了Lambda 表达式需要的所有参数
  • 右侧:指定了Lambda 体,即Lambda 表达式要执行的功能。

② 实例

创建匿名函数实例如下:

Runnable runnable = new Runnable() {
            public void run() {
                System.out.println("Hello !");
            }
        };
//转变为λ表达式
Runnable runnable1=()->System.out.println("Hello !");

匿名内部类作为参数传递:

 TreeSet<String> treeSet = new TreeSet<>(new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return o1.equals(o2)?1:0;
            }
        });
//转变为λ表达式
TreeSet<String> treeSet1 = new TreeSet<>((o1,o2)-> o1.equals(o2)?1:0);

③ 几种语法格式

语法格式一:无参,无返回值,Lambda 体只需一条语句:

Runnable runnable1=()->System.out.println("Hello !");

语法格式二:Lambda 需要一个参数,无返回值:

Consumer<String> fun=(agrs) -> System.out.println(args);

语法格式三:Lambda 只需要一个参数时,参数的小括号可以省略:

Consumer<String> fun=agrs -> System.out.println(args);

语法格式四:Lambda 需要两个参数,并且有返回值:

BinaryOperator<Long> bo=(x,y)->{
	System.out.println("实现函数接口方法 !");
	return x+y;
}

语法格式五:当Lambda 体只有一条语句时,return 与大括号可以省略:

BinaryOperator<Long> bo=(x,y)->x+y;
}

语法格式六:数据类型可以省略,因为可由编译器推断得出,称为“类型推断”:

//如下 Long 可以省略
BinaryOperator<Long> bo=(Long x, Long y)->{
	System.out.println("实现函数接口方法 !");
	return x+y;
}

④ 什么是“类型推断”?

上述Lambda 表达式中的参数类型都是由编译器推断得出的。Lambda 表达式中无需指定类型,程序依然可以编译,这是因为javac根据程序的上下文,在后台推断出了参数的类型。Lambda 表达式的类型依赖于上下文环境,是由编译器推断出来的。这就是所谓的“类型推断”。

即,Lambda表达式本质上是对接口中方法的实现。"类型推断"和Lambda表达式都是jdk1.8提供的语法糖,使代码更简洁。

⑤ 函数式接口

需要注意的是Lambda需要函数式接口的支持。那么什么是函数式接口?接口中只有一个抽象方法,则称之为函数式接口。你可以通过Lambda 表达式来创建该接口的对象。(若Lambda 表达式抛出一个受检异常,那么该异常需要在目标接口的抽象方法上进行声明)。

如下所示,定义一个函数式接口:

@FunctionalInterface
public interface MyFunction {
	
	public String getValue(String str);
}

Lambda测试代码如下:

//需求:对一个数进行运算
@Test
public void test6(){
	Integer num = operation(100, (x) -> x * x);
	System.out.println(num);
	
	System.out.println(operation(200, (y) -> y + 200));
}
	
public Integer operation(Integer num, MyFun mf){
	return mf.getValue(num);
}

⑥ Java 内置四大核心函数式接口

函数式接口 参数类型 返回类型 用途
Consumer<T>消费型接口 T void 对类型为T的对象应用操作,包含方法:void accept(T t)
Supplier<T>供给型接口 T 返回类型为T的对象,包含方法:T get();
Function<T,R>函数型接口 T R 对类型为T的对象应用操作,并返回结果。
结果是R类型的对象。包含方法:R apply(T t);
Predicate<T>断定型接口 T boolean 确定类型为T的对象是否满足某约束,并返回boolean 值。
包含方法boolean test(T t);

四大函数式接口例子:

//Predicate<T> 断言型接口:
@Test
public void test4(){
	List<String> list = Arrays.asList("Hello", "Janus", "Lambda", "www", "ok");
	List<String> strList = filterStr(list, (s) -> s.length() > 3);
	
	for (String str : strList) {
		System.out.println(str);
	}
}

//需求:将满足条件的字符串,放入集合中
public List<String> filterStr(List<String> list, Predicate<String> pre){
	List<String> strList = new ArrayList<>();
	
	for (String str : list) {
		if(pre.test(str)){
			strList.add(str);
		}
	}
	
	return strList;
}

//Function<T, R> 函数型接口:
@Test
public void test3(){
	String newStr = strHandler("\t\t\t 我爱你祖国母亲   ", (str) -> str.trim());
	System.out.println(newStr);
	
	String subStr = strHandler("我爱你祖国母亲", (str) -> str.substring(2, 5));
	System.out.println(subStr);
}

//需求:用于处理字符串
public String strHandler(String str, Function<String, String> fun){
	return fun.apply(str);
}

//Supplier<T> 供给型接口 :
@Test
public void test2(){
	List<Integer> numList = getNumList(10, () -> (int)(Math.random() * 100));
	
	for (Integer num : numList) {
		System.out.println(num);
	}
}

//需求:产生指定个数的整数,并放入集合中
public List<Integer> getNumList(int num, Supplier<Integer> sup){
	List<Integer> list = new ArrayList<>();
	
	for (int i = 0; i < num; i++) {
		Integer n = sup.get();
		list.add(n);
	}
	
	return list;
}

//Consumer<T> 消费型接口 :
@Test
public void test1(){
	happy(10000, (m) -> System.out.println("Welcome again,消费:" + m + "元"));
} 

public void happy(double money, Consumer<Double> con){
	con.accept(money);
}

其他接口如下所示:

函数式接口 参数类型 返回类型 用途
BiFunction<T,U,R> T,U R 对类型为T,U参数应用操作,返回R类型的结果。包含方法为R apply(Tt,Uu);
UnaryOperator<T>
(Function子接口)
T T 对类型为T的对象进行一元运算,并返回T类型的结果。包含方法为T apply(T t);
BinaryOperator<T>
(BiFunction子接口)
T,T T 对类型为T的对象进行二元运算,并返回T类型的结果。包含方法为T apply(T t1,T t2);
BiConsumer<T,U> T,U void 对类型为T,U参数应用操作。包含方法为void accept(T t,U u)
ToIntFunction<T>
ToLongFunction<T>
ToDoubleFunction<T>
T int long double 分别计算int、long、double、值的函数
IntFunction<R>
LongFunction<R>
DoubleFunction<R>
int long double R 参数分别为int、long、double类型的函数

【4】方法引用与构造器引用、数组引用

① 方法引用

当要传递给Lambda体的操作,已经有实现的方法了,可以使用方法引用!

方法引用:使用操作符“::” 将方法名和对象或类的名字分隔开来。

如下三种主要使用情况:

对象::实例方法
类::静态方法
类::实例方法

注意:

  • 方法引用所引用的方法的参数列表与返回值类型,需要与函数式接口中抽象方法的参数列表和返回值类型保持一致!
  • 若Lambda 的参数列表的第一个参数,是实例方法的调用者,第二个参数(或无参)是实例方法的参数时,格式: ClassName::MethodName

测试代码如下:

@Test
public void test1(){
	//对象
	PrintStream ps = System.out;
	//lambda常规表达式
	Consumer<String> con = (str) -> ps.println(str);
	con.accept("Hello World!");
	
	System.out.println("--------------------------------");
	//对象::方法
	Consumer<String> con2 = ps::println;
	con2.accept("Hello Java8!");
	
	//不再拆分
	Consumer<String> con3 = System.out::println;
}
//对象的引用 :: 实例方法名
@Test
public void test2(){
	Employee emp = new Employee(101, "张三", 18, 9999.99);
	//lambda表达式
	Supplier<String> sup = () -> emp.getName();
	System.out.println(sup.get());
	
	System.out.println("----------------------------------");
	//对象::实例方法
	Supplier<String> sup2 = emp::getName;
	System.out.println(sup2.get());
}
//类名 :: 静态方法名
@Test
public void test4(){
	Comparator<Integer> com = (x, y) -> Integer.compare(x, y);
	
	System.out.println("-------------------------------------");
	
	Comparator<Integer> com2 = Integer::compare;
}
//类名 :: 实例方法名
@Test
public void test5(){
	//lambda表达式
	BiPredicate<String, String> bp = (x, y) -> x.equals(y);
	System.out.println(bp.test("abcde", "abcde"));
	
	System.out.println("-----------------------------------------");
	//类名 :: 实例方法名
	BiPredicate<String, String> bp2 = String::equals;
	System.out.println(bp2.test("abc", "abc"));
	
	System.out.println("-----------------------------------------");
	
	//lambda表达式
	Function<Employee, String> fun = (e) -> e.show();
	System.out.println(fun.apply(new Employee()));
	
	System.out.println("-----------------------------------------");
	//类名 :: 实例方法名
	Function<Employee, String> fun2 = Employee::show;
	System.out.println(fun2.apply(new Employee()));
	
}

② 构造器引用

格式:ClassName::new

与函数式接口相结合,自动与函数式接口中方法兼容。可以把构造器引用赋值给定义的方法,与构造器参数
列表要与接口中抽象方法的参数列表一致!

测试代码:

@Test
public void test6(){
	//原始lambda表达式
	Supplier<Employee> sup = () -> new Employee();
	System.out.println(sup.get());
	
	System.out.println("------------------------------------");
	//构造器引用
	Supplier<Employee> sup2 = Employee::new;
	System.out.println(sup2.get());
}
//构造器引用
@Test
public void test7(){
	//函数型接口,一个参数T,一个返回值R,Employee同样需要有一个一个参数的构造器
	Function<String, Employee> fun = Employee::new;
	
	//函数型接口,两个参数T, U,一个返回值R,Employee同样需要有一个两个参数的构造器
	BiFunction<String, Integer, Employee> fun2 = Employee::new;
}


③ 数组引用

格式: type[] :: new

测试代码如下:

@Test
public void test8(){
	//普通lambda表达式
	Function<Integer, String[]> fun = (args) -> new String[args];
	String[] strs = fun.apply(10);
	System.out.println(strs.length);
	
	System.out.println("--------------------------");
	//数组引用
	Function<Integer, String[]> fun2 = String[] :: new;
	String[] strs = fun2.apply(20);
	System.out.println(strs .length);
}

猜你喜欢

转载自blog.csdn.net/J080624/article/details/84976155