JavaInterview
  • README
  • 架构篇
    • 分布式一致性协议
    • 设计模式
    • ElasticSearch
    • MySQL
    • Redis
    • UML 图总结
  • 大数据篇
    • Hadoop 架构
    • Hive
    • Hive 函数
    • kafka_1
    • MaxList以及Set模块
  • 书籍总结
  • 代码篇
    • 动态规划(Dynamic Programming)
    • order_print_num
  • IO 篇
    • 多线程 N 次写文件
    • 多线程、进程、多核 CPU 详细介绍
  • Java 基础知识
    • 异常介绍
    • StringBuffer 和 StringBuilder
    • 线程池
    • 数据结构篇
      • BlockingQueue 和 BlockingDeque 内部实现分析
    • Java8
    • 关键字篇
      • 关键字-transient
      • 关键字-volatile
  • 深入浅出 JVM
    • garbage_collectors
    • JVM 参数
  • README
  • machinelearning
    • model
    • 推荐系统整理
    • tensorflow 入门
  • 排序篇
    • 冒泡排序
    • 基数排序
    • 选择排序
    • 插入排序
    • 希尔排序
    • 归并排序
    • 快速排序
    • 堆排序
    • 计数排序
    • 桶排序
  • Web 篇
    • JavaWeb 中 POJO、BO、VO、DO、DTO、DAO、PO 详细介绍
    • Filter 和 Interceptor 详解
    • HTTP 请求的完整过程
    • Spring 配置
    • Spring IoC
    • Spring 全家桶
Powered by GitBook
On this page
  • 行为参数化(函数式接口)
  • Stream API
  • Lambada 表达式(链式编程)
  • 默认方法

Was this helpful?

  1. Java 基础知识

Java8

分享 Java8 的新特性。

行为参数化(函数式接口)

  1. 筛选某种颜色的苹果

  2. 筛选重量大于某个值的苹果

Java8 之前的代码

public class Apple {

    public static List<Apple> filterApplesByColor(List<Apple> inventory, String color) {
        List<Apple> result = new ArrayList<Apple>();
        for (Apple apple: inventory){
            if ( apple.getColor().equals(color) ) { 
                result.add(apple);
            } 
        }
        return result;
    }

    public static List<Apple> filterApplesByWeight(List<Apple> inventory, int weight) {
        List<Apple> result = new ArrayList<Apple>();
        for (Apple apple: inventory){
            if ( apple.getWeight() > weight ){ 
                result.add(apple);
            } 
        }
        return result;
    }
}

Java8 的代码简化

@FunctionalInterface
public interface ApplePredicate{
    boolean test (Apple apple);
}

public class ProgressDemo {

    public static List<Apple> processApple(List<Apple> appleList, ApplePredicate p) {
        List<Apple> res = new ArrayList<>();
        for (Apple apple : appleList) {
            if (p.test(apple)) {
                res.add(apple);
            }
        }
        return res;
    }

}

Stream API

  1. stream()

  2. parallelStream()

    非线程安全的; 默认线程池的数量就是处理器的数量,特殊场景下可以使用系统属性: -Djava.util.concurrent.ForkJoinPool.common.parallelism={N} 调整

Lambada 表达式(链式编程)

基本语法

  1. (parameters) -> expression

  2. (parameters) -> { statements; }

默认方法

实现有 default 方法的接口, 可以重写 default 方法,不重写则默认使用 interface 中的默认方法。 接口有默认方法之后,个人觉得接口和抽象类之间的区别更小了。

public interface DefaultInterface {

    void test();

    default String getName() {
        return "default";
    }
}
PreviousBlockingQueue 和 BlockingDeque 内部实现分析Next关键字篇

Last updated 5 years ago

Was this helpful?