关于java:Java8新特性

9次阅读

共计 14281 个字符,预计需要花费 36 分钟才能阅读完成。

Java8 新个性
接口中默认办法润饰为一般办法 #
在 jdk8 之前,interface 之中能够定义变量和办法,变量必须是 public、static、final 的,办法必须是 public、abstract 的,因为这些修饰符都是默认的。

接口定义办法:public 形象办法 须要子类实现

接口定义变量:public、static、final

在 JDK 1.8 开始 反对应用 static 和 default 润饰 能够写办法体,不须要子类重写。

办法:

一般办法 能够有办法体

形象办法 没有办法体须要子类实现 重写。

案例

public interface JDK8Interface {

/*
* 默认就是 public abstract  JDK7 之前不能有办法体
* */
void add();

/*
* jdk8 提供默认实现
* */
default void  get() {System.out.println("default 办法能够写办法体");
}

static void getStaticOrder() {System.out.println("静态方法能够写办法体");
}

}
子类实现接口

public class JDK8InterfaceImpl implements JDK8Interface {

/*
* 子类实现接口 没有强制要求重写 default 和 static 办法
* */
@Override
public void add() {System.out.println("add 办法");
}

}
办法调用

public class Test01 {

public static void main(String[] args) {JDK8Interface jdk8Interface=new JDK8InterfaceImpl();
    jdk8Interface.add();
    jdk8Interface.get();

    JDK8Interface.getStaticOrder();}

}
image-20211018202027296

Lambda 表达式 #
是一个匿名函数,简化咱们调用匿名函数的过程

Lambda 益处:简化咱们匿名外部类的调用。

Lambda+ 办法引入 代码变得更加精简。

public static void main(String[] args) {// 应用匿名外部类的形式调用

// new OrderService(){
// @Override
// public void addOrder() {
// System.out.println(“addorder”);
// }
// }.addOrder();

    ((OrderService) () -> System.out.println("addorder")).addOrder();

// new Thread(new Runnable() {
// @Override
// public void run() {
// System.out.println(Thread.currentThread().getName()+” 运行 ”);
// }
// }).start();

    new Thread(() -> System.out.println(Thread.currentThread().getName()+"运行")).start();}

Lambda 表达式的标准 #
应用 Lambda 表达式 依赖于函数接口

在接口中只可能容许有一个形象办法

在函数接口中定义 object 类中办法

应用默认或者静态方法

@FunctionalInterface 示意该接口为函数接口

Java 中应用 Lambda 表达式的标准,必须是为函数接口

函数接口的定义:在该接口中只能存在一个形象办法,该接口称作为函数接口

@FunctionalInterface
public interface MyFunctionalInterface {

void  get();

default void add() {}
String toString();

}
常见例如 Runnable 接口

image-20211018221019469

办法调用

public static void main(String[] args) {((MyFunctionalInterface) () -> System.out.println()).get();}

Lambda 根底语法 #
()– 参数列表
-> 分隔
{} 办法体
(函数接口的参数列表 不须要写类型 须要定义参数名称)->{办法体}

无参办法调用 #
@FunctionalInterface
public interface MyFunctionalInterface {

void  get();

}

MyFunctionalInterface myFunctionalInterface= ()->{

 System.out.println("应用 lambda 表达式");

};
有参带返回值调用 #
@FunctionalInterface
public interface YouFunctionalInterface {

String get(int i,int j);

}

public static void main(String[] args) {YouFunctionalInterface youFunctionalInter=(i, j)->{return i+"--"+j;};
    System.out.println(youFunctionalInter.get(1, 1));
}

精简版 #
public static void main(String[] args) {

    // 无参办法原始版本
    MyFunctionalInterface functionalInterface=()->{System.out.println("");
    };
    functionalInterface.get();
    // 精简版 1
    ((MyFunctionalInterface)()->{System.out.println("");
    }).get();
    // 精简版 2 在办法体只有一条语句的时候,不须要写大括号了
    MyFunctionalInterface functionalInterface2=()-> System.out.println("");
    // 最终精简版 3
    ((MyFunctionalInterface)()-> System.out.println("")).get();


    // 有参办法
    YouFunctionalInterface youFunctionalInterface=(int i,int j)->{return "";};
    String s = youFunctionalInterface.get(2, 3);

    // 精简版 1
    YouFunctionalInterface youFunctionalInterface1=(i, j)->{return "";};

    // 精简版 2
    YouFunctionalInterface youFunctionalInterface2=(i, j)-> i+"--"+j;
    String s1 = youFunctionalInterface1.get(2, 3);

    // 最终精简版 3
    String s2 = ((YouFunctionalInterface) (i, j) -> i + "--" + j).get(1, 2);
    System.out.println(s2);
}

Lambda 实战案例 #
Foreach#

public static void main(String[] args) {ArrayList<String> arrayList=new ArrayList<>();
    arrayList.add("111");
    arrayList.add("222");
    arrayList.add("333");

// arrayList.forEach(new Consumer<String>() {
// @Override
// public void accept(String s) {
// System.out.println(s);
// }
// });

    arrayList.forEach(s->{System.out.println(s);
    });
}

Lambda 汇合排序 #
public class UserEntity {

private String name;
private Integer age;

public UserEntity(String name, Integer age) {
    this.name = name;
    this.age = age;
}

public String getName() {return name;}

public Integer getAge() {return age;}

@Override
public String toString() {
    return "UserEntity{" +
            "name='" + name + '\'' +
            ", age=" + age +
            '}';
}

}
public static void main(String[] args) {

    ArrayList<UserEntity> userlists = new ArrayList<>();
    userlists.add(new UserEntity("aa", 22));
    userlists.add(new UserEntity("bb", 18));
    userlists.add(new UserEntity("cc", 36));

    userlists.sort(new Comparator<UserEntity>() {
        @Override
        public int compare(UserEntity o1, UserEntity o2) {return o1.getAge()- o2.getAge();}
    });

    // 精简遍历
    userlists.forEach(s-> System.out.println(s));

    // 精简排序
    userlists.sort((o1, o2) -> o1.getAge()- o2.getAge());
}

Java 8 stream 流 #
Stream 是 JDK1.8 中解决汇合的要害抽象概念,Lambda 和 Stream 是 JDK1.8 新增的函数式编程最有亮点的个性了,它能够指定你心愿对汇合进行的操作,能够执行非常复杂的查找、过滤和映射数据等操作。应用 Stream API 对汇合数据进行操作,就相似于应用 SQL 执行的数据库查问。Stream 应用一种相似用 SQL 语句从数据库查问数据的直观形式来提供一种对 Java 汇合运算和表白的高阶形象。Stream API 能够极大进步 Java 程序员的生产力,让程序员写出高效率、洁净、简洁的代码

这种格调将要解决的元素汇合看作一种流,流在管道中传输,并且能够在管道的节点上进行解决,比方筛选,排序,聚合等

img

Stream:十分不便精简的模式遍历汇合实现 过滤、排序等

Stream 创立形式 #
parallelStream 为并行流采纳多线程执行

Stream 采纳单线程执行

parallelStream 效率比 Stream 要高

Stream 将 list 转换为 set#
public static void main(String[] args) {

    ArrayList<UserEntity> userEntities = new ArrayList<>();
    userEntities.add(new UserEntity("aa", 20));
    userEntities.add(new UserEntity("bb", 28));
    userEntities.add(new UserEntity("cc", 35));
    userEntities.add(new UserEntity("dd", 16));

    Stream<UserEntity> stream=userEntities.stream();
    Set<UserEntity> collect = stream.collect(Collectors.toSet());
    collect.forEach(s-> System.out.println(s));

}

set 汇合底层依赖于 map 汇合,map 汇合底层基于 equals 和 hashcode 比拟避免反复

Stream 将 list 转换为 map#
public static void main(String[] args) {

    ArrayList<UserEntity> userEntities = new ArrayList<>();
    userEntities.add(new UserEntity("aa", 20));
    userEntities.add(new UserEntity("bb", 28));
    userEntities.add(new UserEntity("cc", 35));
    userEntities.add(new UserEntity("dd", 16));

    /*
    * list 汇合只有 key  list 转换 map 的时候须要指定 key value,key=username  value=user 对象
    * */
    Stream<UserEntity> stream=userEntities.stream();
    Map<String,UserEntity> collect = stream.collect(Collectors.toMap(new Function<UserEntity,String>() {
        @Override
        public String apply(UserEntity o) {return o.getName();
        }
    }, new Function<UserEntity, UserEntity>() {
        @Override
        public UserEntity apply(UserEntity usrentity) {return usrentity;}
    }));

    // 精简版
    collect.forEach(new BiConsumer<String, UserEntity>() {
        @Override
        public void accept(String s, UserEntity userEntity) {System.out.println(s+","+userEntity);
        }
    });
    // 最终精简版
    collect.forEach((BiConsumer)(s,userEntity)->System.out.println(s+","+userEntity));
}

Stream 将 Reduce 求和 #
public static void main(String[] args) {

    Stream<Integer> integerStream=Stream.of(5,6,7,8);
    Optional<Integer> reduce = integerStream.reduce(new BinaryOperator<Integer>() {
        @Override
        public Integer apply(Integer integer, Integer integer2) {return integer + integer2;}
    });
    System.out.println(reduce);

    ArrayList<UserEntity> userEntities = new ArrayList<>();
    userEntities.add(new UserEntity("aa", 20));
    userEntities.add(new UserEntity("bb", 28));
    userEntities.add(new UserEntity("cc", 35));
    userEntities.add(new UserEntity("dd", 16));

    Optional<UserEntity> sum=userEntities.stream().reduce(new BinaryOperator<UserEntity>() {
        @Override
        public UserEntity apply(UserEntity userEntity, UserEntity userEntity2) {UserEntity userEntity1=new UserEntity("sum",userEntity.getAge()+userEntity2.getAge());
            return userEntity1;
        }
    });
    System.out.println(sum);
}

Stream 求最大最小 #

public static void main(String[] args) {ArrayList<UserEntity> userEntities = new ArrayList<>();
    userEntities.add(new UserEntity("aa", 20));
    userEntities.add(new UserEntity("bb", 28));
    userEntities.add(new UserEntity("cc", 35));
    userEntities.add(new UserEntity("dd", 16));

    Stream<UserEntity> stream=userEntities.stream();
    Optional<UserEntity> min = stream.min(new Comparator<UserEntity>() {
        @Override
        public int compare(UserEntity o1, UserEntity o2) {return o1.getAge() - o2.getAge();}
    });
    System.out.println(min.get());

    // 简化版
    Optional<UserEntity> min1 = stream.min((o1, o2) -> o1.getAge() - o2.getAge());
    System.out.println(min1.get());
}

Stream Match 匹配 #
anyMatch 示意,判断的条件里,任意一个元素胜利,返回 true

allMatch 示意,判断条件里的元素,所有的都是,返回 true

noneMatch 跟 allMatch 相同,判断条件里的元素,所有的都不是,返回 true

public static void main(String[] args) {

    ArrayList<UserEntity> userEntities = new ArrayList<>();
    userEntities.add(new UserEntity("aa", 20));
    userEntities.add(new UserEntity("bb", 28));
    userEntities.add(new UserEntity("cc", 35));
    userEntities.add(new UserEntity("dd", 16));

    Stream<UserEntity> stream=userEntities.stream();

    boolean b = stream.anyMatch(new Predicate<UserEntity>() {
        @Override
        public boolean test(UserEntity userEntity) {return "aa".equals(userEntity.getName());
        }
    });
    System.out.println(b);

    // 简化版
    boolean b1 = stream.anyMatch((userEntity) -> "aa".equals(userEntity.getName()));
    System.out.println(b1);
}

Stream for 循环 #

public static void main(String[] args) {ArrayList<UserEntity> userEntities = new ArrayList<>();
    userEntities.add(new UserEntity("aa", 20));
    userEntities.add(new UserEntity("bb", 28));
    userEntities.add(new UserEntity("cc", 35));
    userEntities.add(new UserEntity("dd", 16));

    Stream<UserEntity> stream=userEntities.stream();
    stream.forEach((userEntity -> System.out.println(userEntity)));
}

Stream filter 过滤器 #

public static void main(String[] args) {ArrayList<UserEntity> userEntities = new ArrayList<>();
    userEntities.add(new UserEntity("aa", 20));
    userEntities.add(new UserEntity("bb", 28));
    userEntities.add(new UserEntity("cc", 35));
    userEntities.add(new UserEntity("dd", 16));

    Stream<UserEntity> stream=userEntities.stream();
    stream.filter(new Predicate<UserEntity>() {
        @Override
        public boolean test(UserEntity userEntity) {return "aa".equals(userEntity.getName()) && userEntity.getAge() >= 18;}
    }).forEach((userEntity -> System.out.println(userEntity)));

    // 精简版
    stream.filter((userEntity)->"aa".equals(userEntity.getName()) && userEntity.getAge() >= 18)
            .forEach((userEntity -> System.out.println(userEntity) ));
}

Stream limit 和 skip#
Limit 从头开始获取

Skip 就是跳过

public static void main(String[] args) {ArrayList<UserEntity> userEntities = new ArrayList<>();
    userEntities.add(new UserEntity("aa", 20));
    userEntities.add(new UserEntity("bb", 28));
    userEntities.add(new UserEntity("cc", 35));
    userEntities.add(new UserEntity("dd", 16));

    Stream<UserEntity> stream = userEntities.stream();
    stream.skip(2).limit(2).forEach((userEntity -> System.out.println(userEntity)));
}

stream 综合案例 #
public static void main(String[] args) {

    ArrayList<UserEntity> userEntities = new ArrayList<>();
    userEntities.add(new UserEntity("mayikt", 20));
    userEntities.add(new UserEntity("meite", 28));
    userEntities.add(new UserEntity("zhangsan", 35));
    userEntities.add(new UserEntity("xiaowei", 16));
    userEntities.add(new UserEntity("mayikt_list", 109));
    userEntities.add(new UserEntity("mayikt_zhangsan", 110));
    userEntities.add(new UserEntity("lisi", 109));
    userEntities.add(new UserEntity("mayikt", 100));
    userEntities.add(new UserEntity("mayikt", 60));


    Stream<UserEntity> stream=userEntities.stream();
    stream.sorted((o1,o2)->o1.getAge()-o2.getAge())
            .filter((userEntity -> "mayikt".equals(userEntity.getName())))
            .limit(3)
            .forEach((userEntity)-> System.out.println(userEntity));
}

并行流与串行流区别 #
串行流:单线程的形式操作;数据量比拟少的时候。

并行流:多线程形式操作;数据量比拟大的时候

原理:Fork join 将一个大的工作拆分 n 多个小的子工作并行执行,最初在统计后果,有可能会十分耗费 cpu 的资源,的确能够提高效率。

留神:数据量比拟少的状况下,不要应用并行流

办法援用 #
什么是办法引入

办法引入:须要联合 lambda 表达式可能让代码变得更加精简

静态方法引入:类名::(动态)办法名称

对象办法引入 类名:: 实例办法名称

实例办法引入 new 对象 对象实例:: 办法引入

构造函数引入 类名::new

须要遵循一个标准:

办法引入 办法参数列表、返回类型与函数接口参数列表与返回类型必须要保持一致。

静态方法引入 #
/*

  • 静态方法引入
  • */
    public class Test01 {
    public static void main(String[] args) {

      MyFunctionalInterface myFunctionalInterface = () -> {
          /* 引入 getStaticMethod 办法 */
          Test01.getStaticMethod();};
      myFunctionalInterface.get();
    
      // 应用办法引入调用办法 必须满足:办法引入的办法必须和函数接口中的办法参数列表 / 返回值肯定保持一致。MyFunctionalInterface messageInterface = Test01::getStaticMethod;
      messageInterface.get();

    }
    public static void getStaticMethod() {

      System.out.println("我是 getMethod");

    }
    }
    实例对象办法引入 #
    public class Test02 {
    public static void main(String[] args) {

      Test02 test02=new Test02();
      MyFunctionalInterface myFunctionalInterface = () -> {
          /* 引入 getStaticMethod 办法 */
          test02.getStaticMethod();};
      myFunctionalInterface.get();
    
      // 精简版
      MyFunctionalInterface messageInterface = test02::getStaticMethod;
      messageInterface.get();
    
}
public  void getStaticMethod() {System.out.println("我是 getMethod2");
}

}
构造函数引入 #

public static void main(String[] args) {UserInterface userInterface=new UserInterface() {
        @Override
        public UserEntity getUser() {return new UserEntity();
        }
    };

    // 精简版
    UserInterface userInterface3=UserEntity::new;
    userInterface2.getUser();}

对象办法引入

public class Test04 {

public static void main(String[] args) {Myservice myservice=new Myservice() {
        @Override
        public String get(Test04 test04) {return test04.objGet();
        }
    };

    Myservice myservice1=(Test04-> Test04.objGet());

    // 精简版  传入 Test04 返回 string 值
    Myservice myservice2=Test04::objGet;


    Function<String,Integer> function=new Function<String, Integer>() {
        @Override
        public Integer apply(String s) {return s.length();
        }
    };
    // 精简版
    Function<String,Integer> function2=String::length;
    System.out.println(function2.apply("dfdf"));

}

@FunctionalInterface
public interface Myservice {

String get(Test04 userEntity);

}
JDK8Optional#
Optional 类是一个能够为 null 的容器对象。如果值存在则 isPresent()办法会返回 true,调用 get()办法会返回该对象。

Optional 是个容器:它能够保留类型 T 的值,或者仅仅保留 null。Optional 提供很多有用的办法,这样咱们就不必显式进行空值检测。

Optional 类的引入很好的解决空指针异样。

判断参数是否为空 #
ofNullable(能够传递一个空对象)

Of(不能够传递空对象)

public static void main(String[] args) {
    String username=null;
    Integer a1 = 1;
    Optional<Integer> a = Optional.ofNullable(a1);
    System.out.println(a.isPresent());//true

    Optional<String> username1 = Optional.ofNullable(username);
    System.out.println(username1.isPresent());//false
}

isPresent 示意后果返回是否为空,true 不为空,返回 false 为空

参数为空能够设定默认值 #

public static void main(String[] args) {
    Integer a1 = null;
    Integer a = Optional.ofNullable(a1).orElse(10);
    System.out.println(a);//10
}

参数实现过滤 #
public static void main(String[] args) {

Integer a1 = 16;
Optional<Integer> a = Optional.ofNullable(a1);
// 判断是否等于 16
boolean present = a.filter(new Predicate<Integer>() {
    @Override
    public boolean test(Integer integer) {return integer.equals(16);
    }
}).isPresent();
System.out.println(present);//true

boolean isPresent = a.filter(a2 -> a2==17).isPresent();
System.out.println(isPresent);//false

}
与 Lambda 表达式联合应用,优化代码 #
优化计划 1#

public static void main(String[] args) {
    // 优化前
    String name = "meite";
    if (name != null) {System.out.println(name);
    }
    // 优化后
    Optional<String> name2 = Optional.ofNullable(name);
    // 当 value 不为空时,则不会调用
    name2.ifPresent(s -> System.out.println(s));
    name2.ifPresent(System.out::print);
}

优化计划 2#
public class Test05 {

private static UserEntity userEntity = null;

public static void main(String[] args) {UserEntity userEntity = Test05.getOrder();
    System.out.println(userEntity);
}
public static UserEntity getOrder() {
    // 优化前
    if (userEntity == null) {return createOrder();
    }
    return userEntity;
     // 优化 1
    return Optional.ofNullable(Test05.userEntity).orElseGet(new Supplier<UserEntity>() {
        @Override
        public UserEntity get() {return createOrder();
        }
    });

    // 优化 2
    return Optional.ofNullable(Test05.userEntity).orElseGet(()-> {Test05.userEntity =createOrder();
       return Test05.userEntity;
    });

    // 精简版
    return Optional.ofNullable(Test05.userEntity).orElseGet(() -> createOrder());
}

private static UserEntity createOrder() {return new UserEntity("ylc", 12);
}

}
优化计划 3#
public class Test06 {

public static void main(String[] args) {String orderName = Test06.getOrderName();
    System.out.println(orderName);
}
public static String getOrderName() {
    // 优化前写法:UserEntity userEntity = new UserEntity("123456", 19);
    if (userEntity != null) {String userEntityName = userEntity.getName();
        if (userEntityName != null) {return userEntityName.toLowerCase();
        }
    }
    // 优化后
    Optional<String> s1 = Optional.ofNullable(userEntity)
            .map((s) -> s.getName())
            .map((s) -> s.toLowerCase());

    return s1.get();}

}

正文完
 0