Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

《Java 8 in Action》读书笔记 #7

Open
thinkerou opened this issue May 8, 2018 · 0 comments
Open

《Java 8 in Action》读书笔记 #7

thinkerou opened this issue May 8, 2018 · 0 comments

Comments

@thinkerou
Copy link
Owner

thinkerou commented May 8, 2018

基础知识

为什么要关心 Java 8

  • 简化代码编写

    • 在 Java 8 之前会写如下类似代码:
    Collections.sort(inventory, new Comparator<Apple>() {
      public int compare(Apple a1, Apple a2) {
        return a1.getWeight().compareTo(a2.getWeight());
      }
    }
    • 在 Java 8 里可以写出如下更简洁的代码:
    inventory.sort(comparing(Apple::getWeight));
    
    • 在 Java 8 里新增了如下内容:
      • 流处理
      • 用行为参数化把代码传递给方法
      • 方法和Lambda作为一等公民
      • 默认方法

通过行为参数化传递代码

  • 行为参数化,就是拿出一个代码块,把它准备好而不去执行它,这个代码块以后可以被程序的其他部分调用,即可以推迟这块代码的执行。
  • 示例:农民为了从库存查找满足不同条件的苹果,会经常变动需求。实现一个从列表中筛选绿苹果的功能。
    • 最初的尝试:对每个属性进行筛选
    public static List<Apple> filterApples(List<Apple> inventory, String color,
        Int weight, Bool flag) {
      List<Apple> result = new ArrayList<>();
      for (Apple apple : inventory) {
        if (flag && apple.getColor().equals(color)) ||
            (!flag && apple.getWeight() > weight)) {
          result.add(apple);
        }
      return result;
    }
    List<Apple> greenApples = filterApples(inventory, "green", 0, true);
    
  • 行为参数化

Lambda 表达式

函数式数据处理

高效 Java 8 编程

超越 Java 8

@thinkerou thinkerou self-assigned this May 8, 2018
@thinkerou thinkerou added this to In progress in 2018年读书项目 May 8, 2018
@thinkerou thinkerou changed the title 《Java8 实战》读书笔记 《Java 8 in Action》读书笔记 Jun 10, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
2018年读书项目
  
In progress
Development

No branches or pull requests

1 participant