stream流详解

Stream流的使用

1)生成流
通过数据源生成流

常见的生成方式:

  1.         Collection 体系的集合可以使用默认方法stream()方法生成流
  2.         Map体系的集合间接的生成流,先获取entryset或keyset然后再调用stream方法
  3.         数组 可以通过Stream接口的静态方法of(T ...values)生成流
 //collection
        List<String> l=new ArrayList<>();
        Stream<String> stream = l.stream();

        Set<String> s =new HashSet<>();
        Stream<String> stream1 = s.stream();
        //Map集合体系
        Map<String,String> map=new HashMap<>();
        Stream<String> stream2 = map.keySet().stream();
        Stream<String> stream3 = map.values().stream();
        Stream<Map.Entry<String, String>> stream4 = map.entrySet().stream();
        //数组通过stream流中的of方法生成流
        String [] a={"agtsd","sdf","sdaffd"};
        Stream<String> gad = Stream.of("gad", "b0", "gfds");
        Stream<String> a1 = Stream.of(a);
        Stream<Integer> integerStream = Stream.of(1, 2, 3, 4, 9);


2)中间操作
一个流后面可以跟一个或者多个中间操作,其中主要的是打开流,做出某种程度的过滤,然后返回一个新的流 给下一个操作使用。

常见中间操作方法

  1. Stream <T>filter(Predicate e):用于对流中的数据进行过滤

                Predicate接口中的方法 boolean test(T t):对给定参数进行判断,返回一个布尔值

  1. Stream <T>limit(long maxsize):返回此流中的元素组成流,截取前指定参数个数的数据
  2. Stream <T>skip(long n):跳过指定参数个数的数据,返回由由该流剩余元素组成的流
  3. static <T>Stream<T>concat(Stream a,Stream b):合并a流和b流为一个流
  4. <T>distinct():返回由该流的 不同元素(根据Object.equals(Object))组成的流)
  5. Stream <T>sorted():返回此流的元素租组成的流,根据自然顺序排序
  6. Stream <T>sorted(Comparator e):返回由该流的元素组成的流,根据提供的Comparator进行排序
  7. <R> Stream <R>map(Function mapper):返回由给定函数应用于此流的元素的结果组成的流
  8. IntStream mapToInt(ToIntFunction e):返回一个InStream 其中包含将给定函数应用于此流的元 素的结果

                IntStream:表示原始int 流
                ToIntFunction接口中的方法 int applyAsInt(T value)
                InStream流中的特有方法 int sum()

常见的函数式接口:

        1.Supplier接口 生产数据 T get()             

               抽象方法: T get():获得结果该方法不需要参数,根据自定义的代码逻辑返回结果

        2.Consumer接口 消费数据 void accept(T t)            

              抽象方法:  void accept(T t):对给定的参数执行此操
              默认方法 :   default Consumer<T>andThen(Consumer after):返回一个组合                                           Consumer。

       3. Predicate接口 校验数据 boolean test(Tt)                       

               抽象方法:boolean test(Tt):对给定的参数进行判断(判逻辑由Lambda表达式实现,返回一个布尔值。

              常用的默认方法:
                        default PredicatecT> negate:返回一个逻的否定对应逻辑非
                        default Predicate>and(T t):返回一个组合断对应短路与
                        default Predicate>or(T t):返回一个组合判断对应短路或

       4. Function接口 更新数据 R apply(T t)

             抽象方法:R apply(T t):将此函数运用于给定的参数

             常用 默认方法:
                default <V>Function andThen(Function after):返回一个组合函数首先将该函数应用于输入,然后将after函数应用于结果

  ArrayList<String> arys  = new ArrayList<>();

        arys.add("张鳗鱼:1");
        arys.add("张三:2");
        arys.add("张张张张:3");
        arys.add("三:4");
        arys.add("张里:5");

        arys.stream().filter(s->s.startsWith("张")).forEach(System.out::println);
        arys.stream().limit(1).forEach(System.out::println);

        arys.stream().skip(1).forEach(System.out::println);
        ArrayList<String> arys1  = new ArrayList<>();

        arys.add("流鳗鱼:1");

        Stream.concat(arys1.stream(),arys.stream());

        arys.stream().sorted().forEach(System.out::println);
        arys.stream().sorted((s1,s2)->{
            Integer i = Integer.valueOf(s1.split(":")[1]);
            Integer j = Integer.valueOf(s2.split(":")[1]);
            return i-j;
        }).forEach(System.out::println);
        arys.stream().map(s->{
            String s1 = s.split(":")[1];
            return Integer.parseInt(s1);
        }).forEach(System.out::println);

        System.out.println(arys.stream().mapToInt(s -> {
            return Integer.parseInt(s.split(":")[1]);
        }).sum());

3)终结操作
一个流中只能有一个终结操作,当这个操作被执行过后,流就被使用光了,无法在被操作,所以这必定是流的最后一个操作

常见的终结操作方法

  • void forEach(Consumer action):对此流的每个元素执行操作

          Consumer接口中的方法 void accept(T t):对给定的参数执行此操作

  • long count()返回此流中的元素数

4)收集操作

将stream流中的数据收集到集合, collect() 方法将数据收集到集合/数组中,还可以对数据进行聚合计算,分组,多级分组,分区,拼接等。

收集方法

<R> R collect(Supplier<R> supplier,
                  BiConsumer<R, ? super T> accumulator,
                  BiConsumer<R, R> combiner);
<R, A> R collect(Collector<? super T, A, R> collector)

Collector接口
工具类collectors提供了具体的收集方法
public static <T>Collector toList():把元素收集到list集合中
public static <T>collector toSet():把元素收集到set集合中

public static collector toMap(Function KEye,Function valuee):把元素收集到map集合

//最大值
Collectors.maxBy();
//最小值
Collectors.minBy();
//总和
Collectors.summingInt();/Collectors.summingDouble();/Collectors.summingLong();
//平均值
Collectors.averagingInt();/Collectors.averagingDouble();/Collectors.averagingLong();
//总个数
Collectors.counting();

ArrayList<String> arys = new ArrayList<>();

arys.add("张鳗鱼:1");
arys.add("张三:2");
arys.add("张张张张:3");
arys.add("三:4");
arys.add("张里:5");
//聚合计算
System.out.println(arys.stream().collect(Collectors.summingInt(s -> Integer.parseInt(s.split(":")[1]))));
System.out.println(arys.stream().collect(Collectors.summarizingInt(s -> Integer.parseInt(s.split(":")[1]))));
System.out.println(arys.stream().collect(Collectors.averagingInt(s -> Integer.parseInt(s.split(":")[1]))));

  • 10
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java 8 引入了一种新的抽象概念 Stream),它使得对数据的处理变得更加简便和高效。Stream 是一种来自数据源的元素队列并支持聚合操作。 Stream API 借助于lambda表达式,极大的提高了Java程序员的生产力,让程序员写出高效率、干净、简洁的代码。同时它提供串行和并行两种模式进行汇聚操作,并发模式能够充分利用多核处理器的优势,使用fork/join并行方式来拆分任务和加速处理过程。 Stream 的特性可以归纳为: - 不是数据结构 - 没有存储元素 - 支持延迟计算 - 支持并行处理 Stream 的操作分为中间操作和终止操作。中间操作会返回一个新的 Stream,我们可以对这个新的 Stream 进行下一步的操作。终止操作则会返回一个最终的结果。 Stream 操作可以分为以下几种: - Intermediate(中间)操作:一个可以后面跟随零个或多个Intermediate操作。其目的主要是打开,做出某种程度的数据映射/过滤,然后返回一个新的,交给下一个操作使用。这类操作都是惰性化的(lazy),就是说,仅仅调用到这类方法,并没有真正开始的遍历。 - Terminal(终止)操作:一个只能有一个 Terminal 操作,当这个操作执行后,就被使用“光”了,无法再被操作。所以这必定是的最后一个操作。Terminal 操作的执行,才会真正开始的遍历,并且会生成一个结果,或者一个 side effect。 Stream API 提供了大量的方法,可以用来完成各种不同的操作,如过滤、映射、筛选、查找、归约等等。这些方法可以分为以下几类: - 转换操作:map、flatMap、filter、distinct、sorted、peek、limit、skip - 聚合操作:forEach、reduce、collect - 匹配操作:allMatch、anyMatch、noneMatch - 查找操作:findFirst、findAny - 统计操作:count、min、max、average、sum Stream API 的使用可以大大简化代码,增加可读性和可维护性。同时,由于它的并行特性,可以有效地提升程序的性能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值