Java 8 的新特性: 

  • Lamdba(匿名函数)

  • Stream(流)

  • 接口新增了默认方法


这些改变会让你编程更容易,用不着再写一些啰嗦的代码。


1、比如你想在 Java 代码中按水果对象的重量去排序这个集合

/** * 水果 * @author ConstXiong * @date 2020-03-11 12:29:02 */class Fruit {  private String type;  private String color;  private double weight;
 public Fruit(String type, String color, double weight) {    this.type = type;    this.color = color;    this.weight = weight;  }
 public String getColor() {    return this.color;  }
 public double getWeight() {    return this.weight;  }
 public String getType() {    return this.type;  }
 @Override  public String toString() {    return String.format("{type:%s,color:%s,weight:%s}", type, color, weight);  }}

在 JDK 8 之前必须这么做

Collections.sort(list, new Comparator<Fruit>() {  @Override  public int compare(Fruit o1, Fruit o2) {    return o1.getWeight() >= o2.getWeight() ? 1 : -1;  }});

在 JDK 8 里面,你可以编写更为简洁的代码,这些代码读起来更接近问题的描述(按重量排序水果)

list.sort((Fruit f1, Fruit f2) -> f1.getWeight() >= f2.getWeight() ? 1 : -1);


list.sort(Comparator.comparing(Fruit::getWeight));



2、获取当前目录下的文件夹

在 JDK 8 之前必须这么做

File[] dirs = new File(".").listFiles(new FileFilter(){  public boolean accept(File file) {    return file.isDirectory();  }});

在 JDK 8 可以这么写

File[] dirs = new File(".").listFiles(File::isDirectory);



3、从水果的集合里获取苹果集合

在 JDK 8 之前必须这么做

List<Fruit> apples = new ArrayList<Fruit>();for (Fruit fruit : list) {  if ("苹果".equals(fruit.getType())) {    apples.add(fruit);  }}

在 JDK 8 可以这么写

List<Fruit> apples = list.stream()        .filter(f -> "苹果".equals(f.getType()))        .collect(Collectors.toList());



4、启动一个线程

JDK 8 之前

new Thread(new Runnable() {  @Override  public void run() {      System.out.println("a thread start");  }}).start();

JDK 8 可以这么写

new Thread(() -> System.out.println("a thread start")).start();


这些都得益于,Java 8 的新特性:Lamdba 表达式(匿名函数)、Stream(流)、接口支持默认方法。

  • Lamdba 表达式:目的是将行为参数化,把函数当成一个参数,传递给方法。让 Java 支持了函数式编程的风格。

  • Stream(流):以声明的方式处理集合数据。把集合看作流, 流在管道中传输, 可以在管道的节点上对流数据进行筛选、排序、聚合等操作的处理。

  • 接口支持默认方法:升级了集合的接口支持 Stream API,为了让基于 Java 8 之前版本不报错,接口中添加了 default 关键字修饰默认实现的方法。


更多相关文章

  1. 详解第三种创建线程的方式-Callable接口
  2. 面试官:为什么静态方法不能调用非静态方法和变量?
  3. ConcurrentHashMap之size()方法
  4. 为什么不推荐使用finalize方法,来看看对垃圾回收有什么影响吧
  5. 【编测编学】接口测试面试题必背(下)

随机推荐

  1. 【转】Android(安卓)SDK Setup使用及注意
  2. 网上的Android教程
  3. 〖Android〗(how-to) fix k860/k860i bul
  4. Android地图开发之OpenStreetMap基础教程
  5. 监听不到android 的 Home 键
  6. Android Notifications通知
  7. Android About AndroidManifest.xml
  8. android 常用组建案例
  9. android viewPage 判断是否到最后一页
  10. Android 的 Button 按钮实现的两种方式