java8笔记_1

来源:互联网 发布:矩阵微分方程 编辑:程序博客网 时间:2024/05/17 23:25

Lambda表达式

MyFunction接口

//函数式接口声明@FunctionalInterfacepublic interface MyFunction {    public String getValue(String str);}

MyFunction2接口

public interface MyFunction2<T,R> {    public R getValue(T t1,T t2);}

TestLambda测试方法

/** * lambda表达式排序:按照年龄排序,年龄一样按照姓名排序 * 倒叙排序:return - * 正序排序:return + * @author Mr.zhang * */public class TestLambda {    List<Employee> emps=Arrays.asList(            new Employee("zhangsan",25,9999.99),            new Employee("lisi",20,999),            new Employee("wangwu",19,999),            new Employee("zhaoliu",20,8888)            );    @Test    public void test1() {        Collections.sort(emps, (e1,e2)->{            if(e1.getAge()==e2.getAge()) {                //return 负的返回倒叙                return -e1.getName().compareTo(e2.getName());            }            else {                //return 负的返回倒叙                return -Integer.compare(e1.getAge(), e2.getAge());            }        });        for(Employee emp:emps) {            System.out.println(emp);        }    }    //需求:处理字符串    public String strHandler(String str,MyFunction my) {        return my.getValue(str);    }    @Test    public void test2() {        String trimstr=strHandler("\t\n\t zhangsanlisi", (str)->str.trim());        System.out.println(trimstr);        String trimstr2=strHandler("abcdef",(str)->str.toUpperCase());        System.out.println(trimstr2);        String str3=strHandler("zhangsanli", (str)->str.substring(2, 5));        System.out.println(str3);    }    //需求:对两个Long型数据进行处理    public void op(Long l1,Long l2,MyFunction2<Long,Long> my) {        System.out.println(my.getValue(l1, l2));    }    @Test    public void test3() {        op(100L,200L,(x,y)->x+y);        op(100L,200L,(x,y)->x*y);    }   }

匿名内部类的使用及Lambda的使用优化

接口式匿名内部类使用

//接口式匿名内部类 interface Vehicle {    public void Drive();}-------------------分割线-------------class Test {    public static void main(String[] args) {        Vehicle v = new Vehicle() {            public void Drive() {                System.out.println("Driving a car!");            }        };        v.Drive();    }}

继承式匿名内部类

public class Car {    public void drive() {        System.out.println("Driving a car!");    }    public static void main(String[] args) {        Car car = new Car() {            public void drive() {                System.out.println("Driving another car!");            }        };        car.drive();    }}输出了:Driving another car! Car引用变量不是引用Car对象,而是Car匿名子类的对象。

Employee 类

public class Employee {    private int id;    private String name;    private Integer age;    private double salary;    private Status status;    public Status getStatus() {        return status;    }    public void setStatus(Status status) {        this.status = status;    }    //省略setter getter 方法    public enum Status{        FREE,        BUSY,        VOCATION;    }}
获取工资大于5000的员工的信息;获取年龄大于35岁的人 分别用匿名内部类、Lambda表达式方式写
//泛型接口public interface MyPredicate<T> {    public boolean test(T t);}----------------分割线-------------------//实现类一:工资大于5000public class FilterEmployeeBySalay implements MyPredicate<Employee> {    @Override    public boolean test(Employee t) {        // TODO Auto-generated method stub        System.out.println(t.getSalary()>5000);        return t.getSalary()>5000;    }}//实现类二:年龄大于35public class FilterEmployeeByAge implements MyPredicate<Employee> {    @Override    public boolean test(Employee t) {        // TODO Auto-generated method stub        return t.getAge()>=35;    }}---------------分割线---------------------//原来的匿名内部类写法,忽略:    @Test    public void test1() {        Comparator<Integer> com=new Comparator<Integer>() {            @Override            public int compare(Integer o1, Integer o2) {                // TODO Auto-generated method stub                return Integer.compare(o1, o2);            }        };        TreeSet<Integer> ts=new TreeSet<Integer>();        System.out.println(ts.hashCode());    }//创建一个集合List<Employee> emp=Arrays.asList(            new Employee(0, "zhangsan",18,9999.99),            new Employee(1,"lisi",20,999),            new Employee(2,"wangwu",36,999),            new Employee(3,"zhaoliu",40,8888)            );//方法:返回年龄大于35的人public List<Employee> filterEmployees(List<Employee> list){            List<Employee> ep=new ArrayList<>();            for(Employee e1:list) {                if(e1.getAge()>= 35) {                    ep.add(e1);                }            }            return ep;    }//方法:获取工资大于5000的员工的信息public List<Employee> filterEmployee2(List<Employee> list){        List<Employee> ep=new ArrayList<>();        for(Employee e1:list) {            if(e1.getSalary()>5000) {                ep.add(e1);            }        }        return ep;    }//优化方式:策略设计模式public List<Employee> fileterEmployee(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 test4(){        List<Employee> list=fileterEmployee(emp, new FilterEmployeeByAge());        for(Employee emp:list){            System.out.println(emp);        }        System.out.println("-----------------------");        List<Employee> list2=fileterEmployee(emp, new FilterEmployeeBySalay());        for(Employee emp2:list2){            System.out.println(emp2);        }    }    //优化方式二:匿名内部类    @Test    public void test5(){        List<Employee> list=fileterEmployee(emp, new MyPredicate<Employee>() {            @Override            public boolean test(Employee t) {                // TODO Auto-generated method stub                return t.getSalary()<=5000;            }        });        for(Employee employee:list) {            System.out.println(employee);        }    }    //优化方式三:Lambda表达式    @Test    public void test6() {        List<Employee> list=fileterEmployee(emp, (e) -> e.getSalary()<=5000 );        list.forEach(System.out::println);    }    //优化方式四:Stream API    @Test    public void test7() {        emp.stream()            .filter((e) -> e.getSalary()>=5000)            .limit(1)//取前  1  个            .forEach(System.out::println);        //获取名字        System.out.println("--------------");        emp.stream()            .map(Employee::getName)            .forEach(System.out::println);    }

Lambda表达式语法

函数式接口的声明@FunctionalInterface
@FunctionalInterfacepublic interface Myfun {    public Integer getValue(Integer num);}
语法:
/** *  * @author Mr.zhang *一:Lambda表达式基础语法:java8新的操作符:-> *      箭头操作符将Lambda表达式拆成两部分 *  左侧:Lambda表达式的参数列表 *  右侧:Lambda表达式所需执行的功能:即Lambda体 *语法格式一:无参数无返回值 *      () ->System.out.println("Hello World"); * *语法格式二:有一个参数无返回值 *语法格式三:若只有一个参数,小括号可以省略 *语法格式四:两个以上的参数,有返回值,并且Lambda体中有多条语句 *  Comparator<Integer> com=(x,y)->{            System.out.println("函数式接口");            return Integer.compare(x, y);        }; * *语法格式五:若Lambda体中只有一条语句,return和{}都可以省略 * *语法格式六:Lambda表达式的参数类型可以省略不写,   JVM编译器可以通过上下文判断类型 * *左右遇一括号省 *左侧推断类型省 *能省则省 * *二:Lambda需要“函数式”接口的方法 *函数式接口:接口中只有一个抽象方法,可使用@FunctionalInterface *      可以检查是否有函数式接口 */public class TestLambda2 {    @Test    public void test1() {        int num=0;//Jdk1.7之前  必须是final        Runnable r=new Runnable() {            @Override            public void run() {                // TODO Auto-generated method stub                System.out.println("Hello World!"+num);            }        };        r.run();        System.out.println("--------------");        Runnable r1=()->System.out.println("Hello Lambda!");        r1.run();    }    @Test    public void test2() {        //()可以省略        //Consumer<String> con=(x)->System.out.println(x);        Consumer<String> con=x->System.out.println(x);        con.accept("123456");    }    @Test    public void test3() {        Comparator<Integer> com=(x,y)->{            System.out.println("函数式接口");            return Integer.compare(x, y);        };        int i=com.compare(5, 3);        System.out.println(i);    }    @Test    public void test4() {        Comparator<Integer> com=(x,y)->             Integer.compare(x, y);        com.compare(5, 6);    }    @Test    public void test5() {        //new HashMap<>()里不用写String,Integer,jdk1.8可以自动识别        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(operation(100, (y)->y+20));    }    public Integer operation(Integer num,Myfun mf) {        return mf.getValue(num);    }

函数式接口四大类型

/** *  * @author Mr.zhang *java 8 四大函数式接口 * *Consumer<T> :消费型接口 *      void accept(T t); * *Supplier<T> :供给型接口 *      T get();         * *Function<T R>函数型接口 *      R apply(T t); * *Predicate<T> :断言型接口 *      boolean test(T t); * */public class TestLambda3 {    public void  happy(double money,Consumer<Double> con) {        con.accept(money);    }    //Consumer<T> 消费型接口    @Test    public void test1() {        happy(10000,(m)->System.out.println(m));    }    //需求:产生指定个数的整数,并放入集合中    public List<Integer> getNumList(int num,Supplier<Integer> sup){        List<Integer> list = new ArrayList<>();        for (int i = 0; i < num; i++) {            Integer e=sup.get();            list.add(e);        }        return list;    }    //Suppier<T> 供给型接口:    @Test    public void test2() {        List<Integer> numList=getNumList(10, ()-> (int)(Math.random()*100));        for (Integer lists:numList) {            System.out.println(lists);        }    }    //需求:用于处理字符串    public String strHandler(String str,Function<String, String> funs) {      return  funs.apply(str);    }    //注意此处 要用Integer    public int strHandler2(String str,Function<String, Integer> funs) {          return  funs.apply(str);        }    //Function    @Test    public void test3() {        String newstr=strHandler("\t\t\t123465 65 ",(str) -> str.trim());        System.out.println(newstr);        int str2=strHandler2("123456 789 11 13", (str)->str.length());        System.out.println("长度----"+str2);    }    //需求:将满足条件的字符串,放入集合中    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;    }    //断言型接口:    @Test    public void test4() {        List<String> list=Arrays.asList("hello","world","Lambda","2017","21");        System.out.println("======");        List<String> list2=filterStr(list, (s)->s.length()>3);        for(String str:list2) {            System.out.println("-------");            System.out.println(str);        }    }

java8方法引用

/** *  * @author Mr.zhang *方法引用: *若Lambda 体中的内容有方法已经实现了,我们可以使用方法引用 *      可以理解为方法引用是Lambda表达式的另外一种的表现形式 * *三种语法格式主要 *  * 对象::实例方法名 * 类 : : 静态方法名字 * 类::实例方法名 *  * 注意: *  a:Lambda体中调用方法的参数列表与返回值类型,要与函数式接口中抽象方法的函数是列表和返回值值类型相同 *  b:若Lambda参数列表中的第一个参数是实例方法的调用者,而第二个参数是实例方法的参数时候,可使用ClassName::method *  * 构造器引用 * 格式: *  ClassName::new * 需要调用的构造器的参数列表要与函数式接口中的抽象方法的参数列表保持一致 *  * 数组引用 *  Type::new *  */public class TestmethodRef {    //    @Test    public void test1() {        Consumer<String> con =(x) -> System.out.println(x);        //        PrintStream ps=System.out;        Consumer<String> con1=ps::println;        Consumer<String> con2=System.out::println;        con1.accept("123456");        con2.accept("321654");    }    //对象::实例方法名    @Test    public void test2() {        Employee emp=new Employee();        emp.setAge(100);        emp.setName("zhangsan");        Supplier<String> sup=()-> emp.getName();        String str=sup.get();        System.out.println(str);        Supplier<Integer> sup2=emp::getAge;        Integer num = sup2.get();        System.out.println(num);    }    //类 : : 静态方法名字    @Test    public void test3() {        Comparator<Integer> com =(x,y) -> Integer.compare(x, y);        //比上行代码简洁        Comparator<Integer> com1=Integer::compare;    }    //类::实例方法名    @Test    public void test4() {        //-------------------------b处        BiPredicate<String, String> bp=(b,p)->b.equals(p);        //方法引用        BiPredicate<String, String> bp2=String::equals;    }    //构造器引用    @Test    public void test5() {        Supplier<Employee> sup=() -> new Employee();        //构造器引用的        Supplier<Employee> sup2 =Employee::new;        Employee emp = sup2.get();        System.out.println(emp);    }    @Test    public void test6() {        Function<Integer,Employee> fun=(x)->new Employee(x);        Function<Integer, Employee> fun2=Employee::new;        Employee emp=fun2.apply(101);        System.out.println(emp);        BiFunction<Integer, Integer, Employee> bf=Employee::new;    }    @Test     public void test7() {        Function<Integer, String[]> fun=(x)-> new String[x];        String[] str=fun.apply(10);        System.out.println(str.length);        Function<Integer, String[]> fun2=String[]::new;        String[] str2=fun2.apply(20);        System.out.println(str2.length);    }
原创粉丝点击