java8 Stream api详解

Stream3个阶段

  1. 创建Stream
  2. Stream中间处理
  3. 终止Steam

img

创建Stream方式

        List<String> list = new ArrayList<>();
        list.stream();
        Stream.of(list);
        list.parallelStream();
        Stream.builder();
        //generate返回无限连续流,为了限制流中元素的数量,我们可以使用Stream.limit方法
        Stream.generate();

函数式基础接口

接口名入参返回描述
Function<T, R>TR接受一个泛型 T 对象,返回一个泛型 R 对象,即参数类型和返回类型可以不同
ConsumerT接受一个泛型 <T> 类型参数,进行处理后无任何返回值,常用于消费数据
PredicateTboolean接受一个泛型 <T> 参数,返回值为布尔类型**。Predicate 常用于数据过滤,如过滤出集合中符合某个条件的元素
SupplierT由于没有参数输入,所以多用于对象创建,类似于一个对象创建工厂。可以使用 Lambda 方式创建任意对象,也可以使用对象构造方法的方法引用创对象
OperatorTTFunction 函数接口的扩展

Stream中间处理

函数名入参返回描述
filterPredicateStream按照条件过滤符合要求的元素, 返回新的stream流
mapFunction<? super T, ? extends R>Stream将已有元素转换为另一个对象类型,一对一逻辑,返回新的stream流
mapToIntToIntFunction<? super T, ? extends R>IntStream将已有元素转换为另一个int对象类型,一对一逻辑,返回新的stream流
mapToLongToLongFunction<? super T, ? extends R>LongStream将已有元素转换为另一个Long对象类型,一对一逻辑,返回新的stream流
mapToDoubleToDoubleFunction<? super T, ? extends R>DoubleStream将已有元素转换为另一个Double对象类型,一对一逻辑,返回新的stream流
flatMapFunction<? super T, ? extends Stream<? extends R>>Stream将已有元素转换为另一个int对象类型,一对多逻辑,即原来一个元素对象可能会转换为1个或者多个新类型的元素,返回新的stream流
flatMapToIntFunction<? super T, ? extends IntStream>IntStream将已有元素转换为另一个对象类型,一对多逻辑,即原来一个元素对象可能会转换为1个或者多个新类型的元素,返回新的stream流
flatMapToLongFunction<? super T, ? extends LongStream>LongStream将已有元素转换为另一个Long对象类型,一对多逻辑,即原来一个元素对象可能会转换为1个或者多个新类型的元素,返回新的stream流
flatMapToDoubleFunction<? super T, ? extends DoubleStream>DoubleStream将已有元素转换为另一个Double对象类型,一对多逻辑,即原来一个元素对象可能会转换为1个或者多个新类型的元素,返回新的stream流
distinctStream对Stream中所有元素进行去重,返回新的stream流(并行流效率低)
sortedStream根据自然顺序进行排序
sortedComparator<? super T> comparatorStream对stream中所有的元素按照指定规则进行排序,返回新的stream流
peekConsumer<? super T>Stream此方法主要用于支持调试,您希望在元素流过管道中的某个点时看到这些元素,返回新的stream流
limitlongStream仅保留集合前面指定个数的元素,返回新的stream流(并行流效率低)
skiplongStream跳过集合前面指定个数的元素,返回新的stream流(并行流效率低)

终止Steam

函数名入参返回描述
forEachConsumer<? super T>无返回值,对元素进行逐个遍历,然后执行给定的处理逻辑
forEachOrdered无返回值,始终遵循顺序,对元素进行逐个遍历,然后执行给定的处理逻辑
toArrayObject[]将流转换为数组
toArrayIntFunction<A[]>A[]将流转换为指定类型数组
reduceT,BinaryOperatorT归约,有默认值或初始值,返回单一结果
reduceBinaryOperatorOptional归约, 返回单一结果Optional
reduceU,BiFunction<U, ? super T, U>,BinaryOperatorU归约,有默认值或初始值,返回单一结果(并行流时第三参数生效)
collectCollector<? super T, A, R>Collector将流转换为指定的类型,通过Collectors进行指定
collectSupplier,BiConsumer<R, ? super T>,BiConsumer<R, R>Supplier将流转换为指定的类型,自定义Collector参数
minComparator<? super T>T返回stream处理后的元素最小值
maxComparator<? super T>T返回stream处理后的元素最大值
countlong返回stream处理后最终的元素个数
anyMatchPredicate<? super T>boolean返回一个boolean值,类似于isContains(),用于判断是否有符合条件的元素
allMatchPredicate<? super T>boolean回一个boolean值,用于判断是否所有元素都符合条件
noneMatchPredicate<? super T>boolean返回一个boolean值, 用于判断是否所有元素都不符合条件
findFirstT找到第一个符合条件的元素时则终止流处理
findAnyT找到任何一个符合条件的元素时则退出流处理,这个对于串行流时与findFirst相同,对于并行流时比较高效,任何分片中找到都会终止后续计算逻辑

案例

public class XStream {

    public static void main(String[] args) {
        List<String> a = new ArrayList<String>();
        a.add("1");
        a.add("2");
        a.add("2");
        a.add("4");
        a.add("3");

        List<String> b = new ArrayList<String>();
        b.add("a");
        b.add("b");
        b.add("c");
        b.add("d");


        List<User> users = new ArrayList<>();

        User user1=new User("马超",18);
        User user2=new User("小乔",16);
        User user3=new User("典韦",27);
        User user4=new User("诸葛亮",24);
        User user5=new User("刘备",23);
        users.add(user1);
        users.add(user2);
        users.add(user3);
        users.add(user4);
        users.add(user5);


        new XStream().maxUser(users);
    }

    public void create(){
        List<String> list = new ArrayList<String>();
        list.add("1");
        list.add("2");
        list.add("3");
        list.add("4");
        Stream<String> stream = list.stream();
        Stream<List<String>> list1 = Stream.of(list);
        Stream<String> stringStream = list.parallelStream();
        Stream.Builder<String> builder = Stream.builder();
        builder.add("1");
        builder.add("2");
        builder.add("3");
        builder.add("4");
        Stream<String> build = builder.build();
        Supplier<String> supplier=()->"aaaa";
        Stream<String> generate = Stream.generate(supplier).limit(3);
        generate.forEach(System.out::println);
    }

    public void filter(List<String> list){
        Predicate<String> predicate=a->!a.equals(2);
        Stream<String> stream = list.stream().filter(predicate);
    }

    public void map(List<String> list){
        Function<String,Integer> function=x->Integer.valueOf(x);
        Stream<Integer> stream = list.stream().map(function);
    }

    public void mapToInt(List<String> list){
        ToIntFunction<String> function= x->Integer.valueOf(x);
        IntStream intStream = list.stream().mapToInt(function);
    }

    public void flatMap(List<String> a,List<String> b){
        List<List<String>> ab=new ArrayList<>();
        ab.add(a);
        ab.add(b);
        List<String> collect = ab.stream().flatMap(Collection::stream).collect(Collectors.toList());
        collect.forEach(System.out::println);
    }

    public void flatMapToInt(List<String> a,List<String> b){
        List<List<String>> ab=new ArrayList<>();
        ab.add(a);
        ab.add(b);
        ArrayList<Integer> collect = ab.stream().flatMapToInt(i -> i.stream().mapToInt(Integer::valueOf)).collect(ArrayList::new, List::add, List::addAll);
        collect.forEach(System.out::println);

    }
    public void distinct(List<String> a){
        List<String> collect = a.stream().distinct().collect(Collectors.toList());
        collect.forEach(System.out::println);
    }

    public void sorted(List<String> a){
        List<String> collect = a.stream().sorted().collect(Collectors.toList());
        collect.forEach(System.out::println);
    }
    public void sorted2(List<String> a){
        List<String> collect = a.stream().sorted(Comparator.comparing(x->!x.equals("2"))).collect(Collectors.toList());
        collect.forEach(System.out::println);
    }
    public void peek(List<String> a){
        List<String> collect = a.stream().peek(System.out::println).sorted(Comparator.comparing(x->!x.equals("2"))).peek(System.out::println).collect(Collectors.toList());
        collect.forEach(System.out::println);
    }
    public void limit(List<String> a){
        List<String> collect = a.stream().limit(2).collect(Collectors.toList());
        collect.forEach(System.out::println);
    }
    public void skip(List<String> a){
        List<String> collect = a.stream().skip(2).collect(Collectors.toList());
        collect.forEach(System.out::println);
    }



    public void forEach(List<String> a){
        a.stream().forEach(System.out::println);
    }

    public void forEachOrdered(List<String> a){
        a.parallelStream().forEachOrdered(System.out::println);
        System.out.println("-------------");
        a.parallelStream().forEach(System.out::println);
    }

    public void toArray(List<String> a){
        Object[] objects = a.stream().toArray();
        System.out.println(objects);
    }

    public void toArray2(List<String> a){
        String[] oarrs = a.stream().toArray(String[]::new);
        System.out.println(oarrs);
    }

    public void reduce(List<String> a){
        Optional<String> reduce = a.stream().reduce((x, y) -> x.concat(y));
        System.out.println(reduce.get());
    }

    public void reduce2(List<String> a){
        String reduce = a.stream().reduce("a",(x, y) -> x.concat(y));
        System.out.println(reduce);
    }

    public void reduce3(List<String> a){
        String reduce1 = a.stream().reduce("a",(x, y) -> x.concat(y),(x, y) -> x.concat(y));
        System.out.println(reduce1);
        String reduce2 = a.parallelStream().reduce("a",(x, y) -> x.concat(y),(x, y) -> x.concat(y));
        System.out.println(reduce2);
    }

    public void collect(List<String> a){
        List<String> collect = a.stream().collect(Collectors.toList());
    }

    public void collect2(List<String> a){
        BiConsumer<List<String>, String> accumulator=(x,y)->{
            if(y.equals("2")){
                x.add(y);
            }
        };
        BiConsumer<List<String>, List<String>> combiner=(x,y)->{
            List<String> collect = y.stream().map(m -> "a" + m).collect(Collectors.toList());
            x.addAll(collect);
        };
        List<String> collect = a.parallelStream().collect(ArrayList::new,accumulator,combiner);
        collect.stream().forEach(System.out::println);
    }


    public void min(List<String> a){
        List<Integer> collect = a.stream().mapToInt(Integer::valueOf).collect(ArrayList::new,ArrayList::add,ArrayList::addAll);
        Optional<Integer> min = collect.stream().min(Comparator.comparing(x -> x));
        System.out.println(min.get());
    }

    public void max(List<String> a){
        List<Integer> collect = a.stream().mapToInt(Integer::valueOf).collect(ArrayList::new,ArrayList::add,ArrayList::addAll);
        Optional<Integer> max = collect.stream().max(Comparator.naturalOrder());
        System.out.println(max.get());
    }

    public void maxUser(List<User> a){
        Optional<User> max = a.stream().max(Comparator.comparing(x -> x.getAge()));
        System.out.println(max.get());
    }

    public void count(List<String> a){
        List<Integer> collect = a.stream().mapToInt(Integer::valueOf).collect(ArrayList::new,ArrayList::add,ArrayList::addAll);
        long count = collect.stream().count();
        System.out.println(count);
    }

    public void anyMatch(List<String> a){
        boolean b = a.stream().anyMatch(m -> m.equals("2"));
        System.out.println(b);
    }

    public void allMatch(List<String> a){
        boolean b = a.stream().allMatch(m -> !m.equals("3"));
        System.out.println(b);
    }

    public void noneMatch(List<String> a){
        boolean b = a.stream().noneMatch(m -> m.equals("7"));
        System.out.println(b);
    }

    public void findFirst(List<String> a){
        Optional<String> first = a.stream().findFirst();
        System.out.println(first.get());
    }

    public void findAny(List<String> a){
        Optional<String> first = a.stream().findAny();
        System.out.println(first.get());
    }
}


版权声明:本文为qq_41639347原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。