java中手写一个简单的Stream流你会吗?

76 阅读1分钟

背景

在函数式编程学习中,遇到一个练习题,手写一个简单的stream流,以前觉得很难,感觉这种高级的东西,自己怎么可能写出来那?但是学完后,感觉其实还好,能难住我们的往往是我们自己,以下是写出来的结果,感觉对自己来说很有意义,在此记录下 做个纪念

代码

package org.example.demo;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;

/**
 * 实现一个简单流
 */
public class Demo09<T> {
    public static void main(String[] args) {
        List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5);
        Demo09.of(integerList)
                .filter(integer -> integer>3)
                .map(integer -> integer+"转换后")
                .forEach(System.out::println);
    }
    /**
     * 需求:
     * 1.通过of方法实现,集合转换成流
     * 2.通过filter方法,实现集合元素过滤
     * 3.通过map方法,实现集合元素转换
     * 4.通过foreach方法,实现集合元素遍历
     */

    // 创建一个私有的构造器
    private Demo09(Collection<T> collection){
        this.collection = collection;
    }
    // 创建一个集合属性
    private Collection<T> collection;

    // 相当于一个工厂方法
    public static <T> Demo09<T> of(Collection<T> collection){
        return new Demo09<T>(collection);
    }

    private Demo09<T> filter(Predicate<T> predicate){
        List<T> filterCollection = new ArrayList<>();
        // 这里的操作 应该是对自己的集合进行,所以要对collection进行操作
        for (T t : collection) {
            if(predicate.test(t)){
                filterCollection.add(t);
            }
        }
        return new Demo09<>(filterCollection);
    }

    private <R> Demo09<R> map(Function<T,R> function){
        List<R> mapCollection = new ArrayList<>();
        for (T t : collection) {
            R result = function.apply(t);
            mapCollection.add(result);
        }
        return new Demo09<>(mapCollection);
    }

    private  void forEach(Consumer<T> consumer){
        for (T t : collection) {
            consumer.accept(t);
        }
    }
}