Java8新特性

Posted minge0001

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java8新特性相关的知识,希望对你有一定的参考价值。

1. Java8新特性_简介

HashMap在jdk1.7和jdk1.8中区别

jdk1.7:数组+链表

jdk1.8:数组+链表+红黑树
当哈希碰撞即链表上个数大于8并且总容量个数大于64,链表转成红黑树

红黑树除了添加以外,其他(查询、删除)效率都比链表高
扩容后重排序,不用重新运算hashCode值,直接找对应元素在原来哈希表的总长度加上它当前所在哈希表的位置

HashSet,同理

ConcurrentHashMap

jdk1.7
并发级别:16
锁+段机制:默认16段,每段默认16表
段太多浪费空间,段太少导致每段元素过多效率遍地

jdk1.8
CAS
无锁算法
CAS是底层操作系统支持的算法,效率高

Java 8新特性简介

  • 速度更快
  • 代码更少(增加了新的语法Lambda表达式)
  • 强大的Stream API
  • 便于并行
  • 最大化减少空指针异常 Optional

2. 为什么使用 Lambda 表达式

1-Lambda表达式

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

package day01.com.lm.java8;

import java.util.Objects;

public class Employee {
    private int id;
    private String name;
    private Integer age;
    private double salary;
    private Status status;

    public Employee(String name, Integer age, double salary, Status status) {
        this.name = name;
        this.age = age;
        this.salary = salary;
        this.status = status;
    }

    public Employee() {
        super();
    }

    public Employee(int id) {
        this.id = id;
    }

    public Employee(String name, Integer age, double salary) {
        this.name = name;
        this.age = age;
        this.salary = salary;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }

    public Status getStatus() {
        return status;
    }

    public void setStatus(Status status) {
        this.status = status;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "id=" + id +
                ", name='" + name + '\\'' +
                ", age=" + age +
                ", salary=" + salary +
                ", status=" + status +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Employee employee = (Employee) o;
        return id == employee.id &&
                age == employee.age &&
                Double.compare(employee.salary, salary) == 0 &&
                Objects.equals(name, employee.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, name, age, salary);
    }

    public enum Status {
        FREE,
        BUSY,
        VOCATION
    }
}
package day01.com.lm.java8;

public interface MyPredicate<T> {

    public boolean test(T t);
}
package day01.com.lm.java8;

public class FilterEmployeeByAge implements MyPredicate<Employee> {

    @Override
    public boolean test(Employee t) {
        return t.getAge() >= 35;
    }
}
package day01.com.lm.java8;

public class FilterEmployeeBySalary implements MyPredicate<Employee> {
    @Override
    public boolean test(Employee t) {
        return t.getSalary() >= 5000;
    }
}
package day01.com.lm.java8;

import org.junit.Test;

import java.util.*;

public class TestLambda1 {

    //原来的匿名内部类
    public void test1() {
        Comparator<Integer> com = new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return Integer.compare(o1, o2);
            }
        };

        TreeSet<Integer> ts = new TreeSet<>(com);
    }

    //Lambda 表达式
    public void test2() {
        Comparator<Integer> com = (x, y) -> Integer.compare(x, y);
        TreeSet<Integer> ts = new TreeSet<>(com);
    }

    List<Employee> employees = Arrays.asList(
            new Employee("张三", 18, 9999.99),
            new Employee("李四", 38, 5555.99),
            new Employee("王五", 50, 6666.66),
            new Employee("赵六", 16, 3333.33),
            new Employee("田七", 8, 7777.77)
    );

    //需求:获取当前公司中员工年龄大于35的员工信息
    @Test
    public void test3() {
        List<Employee> list = filterEmployees(this.employees);

        for (Employee employee : list) {
            System.out.println(employee);
        }
    }

    public List<Employee> filterEmployees(List<Employee> list) {
        List<Employee> emps = new ArrayList<>();
        for (Employee emp : list) {
            if (emp.getAge() >= 35) {
                emps.add(emp);
            }
        }
        return emps;
    }

    //需求:获取当前公司中员工工资大于5000的员工信息
    public List<Employee> filterEmployees2(List<Employee> list) {
        List<Employee> emps = new ArrayList<>();
        for (Employee emp : list) {
            if (emp.getSalary() >= 5000) {
                emps.add(emp);
            }
        }
        return emps;
    }

    //优化方式一:策略设计模式
    @Test
    public void test4() {
        List<Employee> list = filterEmployee(employees, new FilterEmployeeByAge());

        for (Employee employee : list) {
            System.out.println(employee);
        }

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

        List<Employee> list2 = filterEmployee(employees, new FilterEmployeeBySalary());

        for (Employee employee : list2) {
            System.out.println(employee);
        }
    }

    public List<Employee> filterEmployee(List<Employee> list, MyPredicate<Employee> mp) {
        List<Employee> emps = new ArrayList<>();
        for (Employee employee : list) {
            if (mp.test(employee)) {
                emps.add(employee);
            }
        }
        return emps;
    }

    //优化方式二:匿名内部类
    @Test
    public void test5() {
        List<Employee> list = filterEmployee(employees, new MyPredicate<Employee>() {
            @Override
            public boolean test(Employee t) {
                return t.getSalary() <= 5000;
            }
        });

        for (Employee employee : list) {
            System.out.println(employee);
        }
    }

    //优化方式三:Lambda表达式
    @Test
    public void test6() {
        List<Employee> list = filterEmployee(employees, (e) -> e.getSalary() <= 5000);
        list.forEach(System.out::println);
    }

    //优化方式四:Stream API
    @Test
    public void test7() {
        employees.stream()
                .filter((e) -> e.getSalary() >= 5000)
                .limit(2)
                .forEach(System.out::println);

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

        employees.stream()
                .map(Employee::getName)
                .forEach(System.out::println);
    }
}

3. Java8新特性_Lambda 基础语法

从匿名类到 Lambda 的转换
在这里插入图片描述
从原来使用匿名内部类作为参数传递到Lambda表达式作为参数传递
在这里插入图片描述
Lambda 表达式语法
Lambda 表达式在Java 语言中引入了一个新的语法元素和操作符。这个操作符为 “->” , 该操作符被称
为 Lambda 操作符或箭头操作符。它将 Lambda 分为两个部分:
左侧:指定了 Lambda 表达式需要的所有参数
右侧:指定了 Lambda 体,即 Lambda 表达式要执行的功能。
在这里插入图片描述
在这里插入图片描述
类型推断
上述 Lambda 表达式中的参数类型都是由编译器推断得出的。Lambda 表达式中无需指定类型,程序依然可以编译,这是因为 javac 根据程序的上下文,在后台推断出了参数的类型。Lambda 表达式的类型依赖于上下文环境,是由编译器推断出来的。这就是所谓的“类型推断”

2-函数式接口

什么是函数式接口

  • 只包含一个抽象方法的接口,称为函数式接口
  • 你可以通过 Lambda 表达式来创建该接口的对象。(若 Lambda 表达式抛出一个受检异常,那么该异常需要在目标接口的抽象方法上进行声明)。
  • 我们可以在任意函数式接口上使用 @FunctionalInterface 注解,这样做可以检查它是否是一个函数式接口,同时 javadoc 也会包含一条声明,说明这个接口是一个函数式接口。

自定义函数式接口
在这里插入图片描述

package day01.com.lm.java8;

import org.junit.Test;

import java.util.*;
import java.util.function.Consumer;

/**
 * 一、Lambda表达式的基础语法:Java8中引入了一个新的操作符“->” 该操作符称为箭头操作符或Lambda操作符
 *                             箭头操作符将Lambda表达式拆分成两部分:
 * 左侧:Lambda表达式的参数列表
 * 右侧:Lambda表达式中所需要执行的功能,即Lambda体
 *
 * 语法格式一:无参数,无返回值
 *      () -> System.out.println("Hello Lambda!");
 *
 * 语法格式二:有一个参数,并且无返回值
 *      (x) -> System.out.println(x);
 *
 * 语法格式三:只有一个参数,小括号可以省略不写
 *      x -> System.out.println(x);
 *
 * 语法格式四:有两个以上的参数,有返回值,并且Lambda体有多条语句
 *        Comparator<Integer> com = (x, y) -> {
 *             System.out.println("函数式接口");
 *             return Integer.compare(x, y);
 *         };
 *
 * 语法格式五:若Lambda体中只有一条语句,return和大括号都可以省略不写
 *      Comparator<Integer> com = (x, y) -> Integer.compare(x, y);
 *
 * 语法格式六:Lambda表达式的参数列表的数据类型可以省略不写,因为JVM编译器通过上下文推断出数据类型,即“类型推断”
 *      Comparator<Integer> com = (Integer x, Integer y) -> Integer.compare(x, y);
 *
 * 上联:左右遇一括号省
 * 下联:左侧推断类型省
 * 横批:能省则省
 *
 * 二、Lambda表达式需要“函数式接口”的支持
 * 函数式接口:接口中只有一个抽象方法的接口,称为函数式接口。
 *             可以使用注解@FunctionalInterface修饰可以检查是否是函数式接口
 */
public class TestLambda2 {

    @Test
    public void test1() {//无参数,无返回值
        int num = 0;//jdk1.7前,必须加final

        Runnable r = new Runnable() {
            @Override
            public void run() {
                System.out.println("Hello World!" + num);
            }
        };

        r.run();

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

        Runnable r1 = () -> System.out.println("Hello World!" + num);
        r1.run();
    }

    @Test
    public void test2() {//有一个参数,并且无返回值
        Consumer<String> con = (x) -> System.out.println(x);
        con.accept("民哥威武!");
        //只有一个参数,小括号可以省略不写
        Consumer<String> con2 = x -> System.out.println(x);
        con2.accept("民哥威武!");
    }

    @Test
    public void test3() {//有两个以上的参数,有返回值,并且Lambda体有多条语句
        Comparator<Integer> com = (x, y) -> {
            System.out.println("函数式接口");
            return Integer.compare(x, y);
        };
    }

    @Test
    public void test4() {//若Lambda体中只有一条语句,return和大括号都可以省略不写
        Comparator<Integer> com = (x, y) -> Integer.compare(x, y);
        Comparator<Integer> com2 = (Integer x, Integer y) -> Integer.compare(x, y);
    }

    @Test
    public void test5() {
        String[] strs = {"aaa", "bbb", "ccc"};
//        String[] strs;
//        strs = {"aaa", "bbb", "ccc"};

        List<String> list = new ArrayList<>();

        show(new HashMap<>());
    }

    public void show(Map<String, Integer> map) {

    }

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

        System.out.println

以上是关于Java8新特性的主要内容,如果未能解决你的问题,请参考以下文章

2020了你还不会Java8新特性?Java 8新特性介绍

java8新特性——Lambda表达式

Java8新特性

java8新特性总结

Java8新特性

Java8新特性-官方库新特性