函数式接口与Stream流

175 阅读1分钟

函数式接口与Stream流

作用

  • 函数式接口是为了简化代码(和Lambda表达式配合)
  • Stream流是为了做数据处理

函数式接口

函数式接口: 只有一个方法的接口. 主要为了简化编程模型. 函数式接口都可以用Lambda表达式简化.

/**
* 函数式接口例子
*/
@FunctionalInterface
public interface Runnable {
    public abstract void run();
}

四大函数式接口

  • Function 函数型接口

    @FunctionalInterface
    public interface Function<T, R> {
        R apply(T t);
    }
    
  • Consumer 消费型接口

    @FunctionalInterface
    public interface Consumer<T> {
        void accept(T t);
    }
    
  • Predicate 断定型接口

    @FunctionalInterface
    public interface Predicate<T> {
        boolean test(T t);
    }
    
  • Supplier 供给型接口

    @FunctionalInterface
    public interface Supplier<T> {
        T get();
    }
    

Stream流

集合和数据库都是为了存储, 计算应该交给Stream流.

/**
     * 1.id为偶数
     * 2.年龄必须大于23岁
     * 3.用户名转为大写字母
     * 4.用户名字母倒着排序
     * 5.只输出一个用户
*/
public static void main(String[] args) {
    User u1 = new User(1,"a",21);
    User u2 = new User(2,"b",22);
    User u3 = new User(3,"c",23);
    User u4 = new User(4,"d",24);
    User u5 = new User(6,"e",25);
    List<User> list = Arrays.asList(u1, u2, u3, u4, u5);

    list.stream()
        .filter(u -> u.getId()%2 == 0)
        .filter(u -> u.getAge() > 23)
        .map(u -> u.getName().toUpperCase())
        .sorted((a,b) -> {
            return b.compareTo(a);
        })
        .limit(1)
        .forEach(System.out::println);
}