java8新特性学习

时间:2020-06-30
本文章向大家介绍 java8新特性学习 ,主要包括 java8新特性学习 使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

Lambda表达式:ide

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

 

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

 

List<Employee> emps = Arrays.asList(
            new Employee(101, "张三", 18, 9999.99),
            new Employee(102, "李四", 59, 6666.66),
            new Employee(103, "王五", 28, 3333.33),
            new Employee(104, "赵六", 8, 7777.77),
            new Employee(105, "田七", 38, 5555.55)
    );

    //需求:获取公司中年龄小于 35 的员工信息
    public List<Employee> filterEmployeeAge(List<Employee> emps){
        List<Employee> list = new ArrayList<>();
        
        for (Employee emp : emps) {
            if(emp.getAge() <= 35){
                list.add(emp);
            }
        }
        
        return list;
    }
    
    @Test
    public void test3(){
        List<Employee> list = filterEmployeeAge(emps);
        
        for (Employee employee : list) {
            System.out.println(employee);
        }
    }
    
    //需求:获取公司中工资大于 5000 的员工信息
    public List<Employee> filterEmployeeSalary(List<Employee> emps){
        List<Employee> list = new ArrayList<>();
        
        for (Employee emp : emps) {
            if(emp.getSalary() >= 5000){
                list.add(emp);
            }
        }
        
        return list;
    }

 

public interface MyPredicate<T> {
    public boolean test(T t);    
}

public class FilterEmployeeForAge implements MyPredicate<Employee>{

    @Override
    public boolean test(Employee t) {
        return t.getAge() <= 35;
    }

}

public class FilterEmployeeForSalary implements MyPredicate<Employee> {

    @Override
    public boolean test(Employee t) {
        return t.getSalary() >= 5000;
    }

}

 

//优化方式一:策略设计模式
    public List<Employee> filterEmployee(List<Employee> emps, MyPredicate<Employee> mp){
        List<Employee> list = new ArrayList<>();
        
        for (Employee employee : emps) {
            if(mp.test(employee)){
                list.add(employee);
            }
        }
        
        return list;
    }
    
    @Test
    public void test4(){
        List<Employee> list = filterEmployee(emps, new FilterEmployeeForAge());
        for (Employee employee : list) {
            System.out.println(employee);
        }
        
        System.out.println("------------------------------------------");
        
        List<Employee> list2 = filterEmployee(emps, new FilterEmployeeForSalary());
        for (Employee employee : list2) {
            System.out.println(employee);
        }
    }

 

//优化方式二:匿名内部类
    @Test
    public void test5(){
        List<Employee> list = filterEmployee(emps, new MyPredicate<Employee>() {
            @Override
            public boolean test(Employee t) {
                return t.getId() <= 103;
            }
        });
        
        for (Employee employee : list) {
            System.out.println(employee);
        }
    }

 

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

 

//优化方式四:Stream API
    @Test
    public void test7(){
        emps.stream()
            .filter((e) -> e.getAge() <= 35)
            .forEach(System.out::println);
        
        System.out.println("----------------------------------------------");
        
        emps.stream()
            .map(Employee::getName)
            .limit(3)
            .sorted()
            .forEach(System.out::println);
    }

 

Lambda表达式的基础语法:函数

  ->:称为箭头操做符,或者lambda操做符,箭头操做符把表达式拆分红两份学习

    左侧:表达式的参数列表

    右侧:表达式须要执行的功能, 即Lambda体

 

语法格式一:无参数,无返回值     () -> System.out.println("Hello Lambda!");

@Test
    public void test1(){
        int num = 0;//jdk 1.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 Lambda!");
        r1.run();
    }

 

语法格式二:有一个参数,而且无返回值      (x) -> System.out.println(x)

@Test
    public void test2(){
        Consumer<String> con = (x) -> System.out.println(x);
        con.accept("好好学习,每天向上!");
    }

 

语法格式三:若只有一个参数,小括号能够省略不写    x -> System.out.println(x)

@Test
    public void test2(){
        Consumer<String> con = x -> System.out.println(x);
        con.accept("xxx");
    }

 

语法格式四:有两个以上的参数,有返回值,而且 Lambda 体中有多条语句

@Test
    public void test3(){
        Comparator<Integer> com = (x, y) -> {
            System.out.println("xxxx");
            return Integer.compare(x, y);
        };
    }

 

语法格式五:若 Lambda 体中只有一条语句, return 和 大括号均可以省略不写

@Test
    public void test4(){
        Comparator<Integer> com = (x, y) -> Integer.compare(x, y);
    }

 

语法格式六:Lambda 表达式的参数列表的数据类型能够省略不写,由于JVM编译器经过上下文推断出,数据类型,即“类型推断”   (Integer x, Integer y) -> Integer.compare(x, y);

@Test
    public void test5(){
        String[] strs = {"aaa", "bbb", "ccc"};
        
        List<String> list = new ArrayList<>();
        
        show(new HashMap<>());
    }

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

lambda表达式须要函数式接口的支持:

函数式接口:接口中只有一个抽象方法的接口,称为函数式接口,可使用注解 @FunctionalInterface 修饰,能够检查是不是函数式接口

@FunctionalInterface
public interface Fun {

    public Integer getValue(Integer num);
    
}
//需求:对一个数进行运算
    @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, Fun mf){
        return mf.getValue(num);
    }
//比较两个实体,先按照年龄比较,相同则按照姓名比较
List<Employee> emps = Arrays.asList(
            new Employee(101, "张三", 18, 9999.99),
            new Employee(102, "李四", 59, 6666.66),
            new Employee(103, "王五", 28, 3333.33),
            new Employee(104, "赵六", 8, 7777.77),
            new Employee(105, "田七", 38, 5555.55)
    );
    
    @Test
    public void test1(){
        Collections.sort(emps, (e1, e2) -> {
            if(e1.getAge() == e2.getAge()){
                    return e1.getName().compareTo(e2.getName());
            }else{
                return -Integer.compare(e1.getAge(), e2.getAge());
            }
        });
        
        for (Employee emp : emps) {
            System.out.println(emp);
        }
    }
    
//字符串操做
@FunctionalInterface public interface MyFunction { public String getValue(String str); } //需求:用于处理字符串 public String strHandler(String str, MyFunction mf){ return mf.getValue(str); } @Test public void test2(){ String trimStr = strHandler("\t\t\tjava天下第一 ", (str) -> str.trim()); System.out.println(trimStr); String upper = strHandler("abcdef", (str) -> str.toUpperCase()); System.out.println(upper); String newStr = strHandler("PHP天下第一", (str) -> str.substring(2, 5)); System.out.println(newStr); }
public interface MyFunction2<T, R> {
    public R getValue(T t1, T t2);
    
}

//需求:对于两个 Long 型数据进行处理
    public void op(Long l1, Long l2, MyFunction2<Long, Long> mf){
        System.out.println(mf.getValue(l1, l2));
    }

    @Test
    public void test3(){
        op(100L, 200L, (x, y) -> x + y);        
        op(100L, 200L, (x, y) -> x * y);
    }

java8中内置的四大函数式接口

Customer<T> 消费型接口

  void accept( T t);

//Consumer<T> 消费型接口 :
    @Test
    public void test1(){
        happy(10000, (m) -> System.out.println("这次购物消费" + m + ""));
    } 
    
    public void happy(double money, Consumer<Double> con){
        con.accept(money);
    }

Supplier( T t )  供给型接口

  T get();

//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;
    }

Function<T, R>:函数型接口

  R apply(T t);

//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);
    }

Predicate<T>:断言型接口

  boolean test(T t);

//Predicate<T> 断言型接口:
    @Test
    public void test4(){
        List<String> list = Arrays.asList("java", "php", "android", "ios", ".net");
        List<String> strList = filterStr(list, (s) -> s.length() > 4);
        
        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;
    }

来源:https://www.shangmayuan.com/a/e7720560ffcb436e8c005f89.html

原文地址:https://www.cnblogs.com/droxy/p/13213433.html