首页 > 其他分享 >stream

stream

时间:2024-09-26 16:45:02浏览次数:7  
标签:Hero stream System collect println new out

注:List.of()方法需要1.8以上才支持

1.filter,过滤,关键:Predicate

 Stream.of(
                        new Fruit("草莓", "", "1", "red"),
                        new Fruit("香蕉", "", "2", "yellow"),
                        new Fruit("苹果", "", "3", "green"),
                        new Fruit("橘子", "", "4", "orange"),
                        new Fruit("榴莲", "", "5", "yellow")
                ).filter(fruit -> fruit.getColor().equals("red"))
                .forEach(System.out::println);

2.map,映射,关键:Function

Stream.of(
                        new Fruit("草莓", "", "1", "red"),
                        new Fruit("香蕉", "", "2", "yellow"),
                        new Fruit("苹果", "", "3", "green"),
                        new Fruit("橘子", "", "4", "orange"),
                        new Fruit("榴莲", "", "5", "yellow")
                ).map(Fruit::getColor)
                .forEach(System.out::println);

3.flatMap,扁平化(降维)

Stream.of(
List.of(new Fruit("葡萄", "", "1", "red"),
new Fruit("橙子", "", "2", "yellow"),
new Fruit("火龙果", "", "3", "green"),
new Fruit("橘子", "", "4", "orange")),
List.of(new Fruit("香蕉", "", "2", "yellow"),
new Fruit("苹果", "", "3", "green"),
new Fruit("榴莲", "", "5", "yellow"))
).flatMap(list -> list.stream())
.forEach(System.out::println);

Integer[][] arr = {
{1, 2, 3},
{3, 4, 5},
{5, 6, 7},
};
Arrays.stream(arr).flatMap(array -> Arrays.stream(array))
.forEach(System.out::println);
 

 4.构建流

 4.1 从集合构建

集合.stream()

4.2 从数组构建

Arrays.stream(数组)

4.3 从对象构建

Stream.of(对象)

        //从集合构建
        Arrays.stream(arr).flatMap(array -> Arrays.stream(array))
                .forEach(System.out::println);
        ArrayList<String> list = new ArrayList<>();
        HashSet<String> set = new HashSet<>();
        HashMap<String, String> map = new HashMap<>();
        list.stream().forEach(System.out::println);
        set.stream().forEach(System.out::println);
        map.entrySet().stream().forEach(System.out::println);
        //从数组构建
        int[] array = {1, 2, 3, 4, 5, 6, 7, 8};
        Arrays.stream(array).forEach(System.out::println);
        //从对象构建
        Stream.of(1, 2, 3, 4, 5).forEach(System.out::println);    

合并和截取

     //合并
        Stream<Integer> integerStream1 = Stream.of(1, 2, 3);
        Stream<Integer> integerStream2 = Stream.of(4, 5, 6);
        Stream<Integer> concat = Stream.concat(integerStream1, integerStream2);
        concat.forEach(System.out::println);
        //截取
        //skip(long n) 跳过n个数据,保留剩下的
        //limit(long n) 保留n个数据,剩下的不要
        concat.skip(2).forEach(System.out::println);
        concat.limit(2).forEach(System.out::println);
        concat.skip(2).limit(2).forEach(System.out::println);

    //截取根据条件确定截取位置
    //takeWhile(Predicate p) 条件成立保留,一旦条件不成立,剩下的不要
    //dropWhile(Predicate p) 条件成立舍弃,一旦条件不成立,剩下的保留
    //concat.takeWhile(x->x<3).forEach(System.out::println);
    //concat.dropWhile(x->x<3).forEach(System.out::println);

生成流,不用现有数据生成stream对象

    //生成流,不用现有数据生成stream对象
        //1 简单生成
        //IntStream.range(...)
        IntStream.range(1, 10).forEach(System.out::println);
        IntStream.rangeClosed(1, 9).forEach(System.out::println);
        //2 依赖上一个值生成当前值
        //IntStream.iterate(...) 1,3,5,7,9
        IntStream.iterate(1, x -> x + 2).limit(10).forEach(System.out::println);
        //3 不依赖上一个值生成当前值
        //IntStream.generate(...)
        IntStream.generate(() -> ThreadLocalRandom.current().nextInt(100)).limit(5).forEach(System.out::println);
        //生成随机整数
        ThreadLocalRandom.current().ints(5, 0, 100).forEach(System.out::println);

查找与判断

        //查找与判断
        //查找
        //filter(Predicate p).findAny() 找到任意一个元素
        //filter(Predicate p).findFirst() 找到第一个元素
        //判断
        //1 anyMatch(Predicate p) 一个满足
        //2 allMatch(Predicate p) 都满足
        //3 noneMatch(Predicate p) 都不满足
        IntStream intStream = IntStream.of(1, 2, 3, 4, 5, 6, 7);
        System.out.println(intStream.filter(x -> (x & 1) == 0).findFirst().orElse(-1));
        System.out.println(intStream.filter(x -> (x & 1) == 0).findAny().orElse(-1));
        System.out.println(intStream.anyMatch(x -> (x & 1) == 0));
        System.out.println(intStream.allMatch(x -> (x & 1) == 0));
        System.out.println(intStream.noneMatch(x -> (x & 1) == 0));

去重排序

     //去重
        IntStream.of(1, 2, 3, 1, 2, 4, 5, 6, 7, 1, 2)
                .distinct()
                .forEach(System.out::println);
        //排序
        Stream.of(
                        new Hero("张三", 90),
                        new Hero("李四", 98),
                        new Hero("王老五", 93),
                        new Hero("令狐冲", 95),
                        new Hero("东方不败", 99),
                        new Hero("风清扬", 88),
                        new Hero("独孤求败", 82),
                        new Hero("任我行", 99)
//                ).sorted((a, b) -> a.getStrength() < b.getStrength() ? -1 : a.getStrength() == b.getStrength() ? 0 : 1)
//                ).sorted((a, b) -> Integer.compare(a.getStrength(), b.getStrength()))
//                ).sorted(Comparator.comparingInt(x-> x.getStrength())
//                ).sorted(Comparator.comparingInt(Hero::getStrength))
                ).sorted(Comparator.comparingInt(Hero::getStrength).reversed().thenComparing(x -> x.getName().length()))
                .forEach(System.out::println);
    }

化简,两两合并,只剩一个

适合,最大值,最小值,求和,求个数

        //化简,两两合并,只剩一个
        //适合,最大值,最小值,求和,求个数
        //reduce((p, x)->r)) p上次的合并结果,x当前元素,r本次合并结果
        //reduce(init,(p, x)->r))
        //reduce(init,(p, x)->r),(r1,r2)->r)
        Stream<Hero> heroStream = Stream.of(
                new Hero("张三", 90),
                new Hero("李四", 98),
                new Hero("王老五", 93),
                new Hero("令狐冲", 95),
                new Hero("东方不败", 99),
                new Hero("风清扬", 88),
                new Hero("独孤求败", 82),
                new Hero("任我行", 99)
        );
        //最大值
        Optional<Hero> reduce = heroStream.reduce((h1, h2) -> h1.getStrength() > h2.getStrength() ? h1 : h2);
        System.out.println(reduce);
        Hero hero = heroStream.reduce(new Hero("-", -1), (h1, h2) -> h1.getStrength() > h2.getStrength() ? h1 : h2);
        System.out.println(hero);
        //求总数
        System.out.println(heroStream.map(h -> 1).reduce(0, (a, b) -> a + b));
        long count = heroStream.count();
        Optional<Hero> max = heroStream.max(Comparator.comparingInt(Hero::getStrength));
        Optional<Hero> min = heroStream.min(Comparator.comparingInt(Hero::getStrength));
        int sum = heroStream.mapToInt(Hero::getStrength).sum();
        OptionalDouble average = heroStream.mapToInt(Hero::getStrength).average();

 收集

 //收集,将元素收集入容器
        //.collect(()->c,(c,x)->void)
        // ()->c  创建容器
        // (c,x)->void  将元素x放入容器c
        Stream<String> stringStream = Stream.of("张三", "李四", "王老五", "令狐冲", "东方不败", "风清扬", "独孤求败", "任我行");
        ArrayList<String> result = stringStream.collect(() -> new ArrayList<>(), (list, x) -> list.add(x), (a, b) -> {});
        ArrayList<String> result = stringStream.collect(ArrayList::new, ArrayList::add, (a, b) -> {});
        LinkedHashSet<String> result = stringStream.collect(LinkedHashSet::new, Set::add, (a, b) -> {});
        HashMap<String, Integer> result = stringStream.collect(HashMap::new, (map, x) -> map.put(x, 1), (a, b) -> {
        });
        for (Map.Entry<String, Integer> str : result.entrySet()
        ) {
            System.out.println(str.getKey()+"  "+str.getValue());
        }

        StringBuilder collect = stringStream.collect(StringBuilder::new, StringBuilder::append, (a, b) -> {});
        System.out.println(collect);
        StringJoiner collect = stringStream.collect(() -> new StringJoiner(","), StringJoiner::add, (a, b) -> {});
        System.out.println(collect);

Collectos收集器

        List<String> collect = stringStream.collect(Collectors.toList());
        Set<String> collect1 = stringStream.collect(Collectors.toSet());
        String collect2 = stringStream.collect(Collectors.joining());
        String collect3 = stringStream.collect(Collectors.joining(","));

        for (String s:collect
             ) {
            System.out.println(s);
        }
        Map<String, Integer> collect4 = stringStream.collect(Collectors.toMap(x -> x, x -> 1));
        for (Map.Entry<String, Integer> str : collect4.entrySet()
        ) {
            System.out.println(str.getKey()+"  "+str.getValue());
        }

 下游收集器

        //内层的收集器:下游收集器
        Map<Integer, java.util.List<String>> collect5 = stringStream.collect(Collectors.groupingBy(x -> x.length(), Collectors.toList()));
        for (Map.Entry<Integer, java.util.List<String>> str : collect5.entrySet()
        ) {
            System.out.println(str.getKey()+"  "+str.getValue());
        }
        Map<Integer, String> collect6 = stringStream.collect(Collectors.groupingBy(x -> x.length(), Collectors.joining(",")));
        for (Map.Entry<Integer, String> str : collect6.entrySet()
        ) {
            System.out.println(str.getKey()+"  "+str.getValue());
        }
        //mapping(x->y,dc)
        Map<Integer, java.util.List<Integer>> collect =
                heroStream.collect(Collectors.groupingBy(h -> h.getName().length(), Collectors.mapping(h -> h.getStrength(), Collectors.toList())));
        for (Map.Entry<Integer, java.util.List<Integer>> str : collect.entrySet()
        ) {
            System.out.println(str.getKey()+"  "+str.getValue());
        }

基本流

        IntStream intStream = IntStream.of(1, 2, 3, 4, 5, 6);
        LongStream longStream = LongStream.of(1L, 2L, 3L);
        DoubleStream doubleStream = DoubleStream.of(1.0, 2.0, 3.0);
        System.out.println(intStream.sum());
        System.out.println(intStream.min());
        System.out.println(intStream.max());
        System.out.println(intStream.average());
        IntSummaryStatistics intSummaryStatistics = intStream.summaryStatistics();
        System.out.println(intSummaryStatistics.getSum());
        System.out.println(intSummaryStatistics.getMax());
        System.out.println(intSummaryStatistics.getMin());
        System.out.println(intSummaryStatistics.getCount());
        System.out.println(intSummaryStatistics.getAverage());

stream 流的特性

1.一次使用

流只能被消费一次

2.两类操作

(中间操作lazy,终结操作eager)

 

 并行流

数据量问题:数据量大时才推荐并行流。

线程会无限增加吗:跟cpu能处理的线程数相关

收尾的意义:转不可变集合,stringbuilder转string

是否线程安全:不会有线程安全问题

        java.util.List<Integer> collect = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9)
                .parallel()
                .collect(Collector.of(
                        () -> new ArrayList(),  //如何创建容器
                        (list, x) -> list.add(x),//如何向容器添加数据
                        (list1, list2) -> {
                            list1.addAll(list2);
                            return list1;
                        },//如何合并两个容器的数据
                        list -> list
                        //特性:容器是否支持并发,是否需要收尾,是否需要保持收集顺序
                ));

特性:容器是否支持并发(默认不支持),是否需要收尾(默认收尾),是否需要保持收集顺序(默认保证)

 

标签:Hero,stream,System,collect,println,new,out
From: https://www.cnblogs.com/gstszbc/p/18407945

相关文章

  • StreamInTest
    packagecom.shrimpking.t1;importjava.io.BufferedReader;importjava.io.InputStreamReader;/***CreatedbyIntelliJIDEA.**@Author:Shrimpking*@create2024/9/1410:45*/publicclassStreamInTest{publicstaticvoidmain(String[]args)......
  • Stream管理事件流
    文章目录概念介绍管理方法示例代码我们在上一章回中介绍了事件流相关的内容,本章回中将介绍如何管理Stream事件流。闲话休提,言归正传,让我们一起TalkFlutter吧。概念介绍我们简单回顾一下前面的知识:Stream把相关的事件组成了事件流,并且提供方法来监听这些事件的运......
  • `std::string_view`(c++17) 和 `std::stringstream` 使用区别·
    std::string_view和std::stringstream都是C++中处理字符串的工具,但它们的设计目标和使用场景非常不同。我们可以通过几方面进行对比。1.设计目的和核心功能std::string_view:设计用于只读访问字符串或字符序列。是一个轻量级的字符串视图,不会持有字符串的数据,仅仅是对......
  • faststream 自己的asgi 实现
    faststream目前自己包含了一个asgi的实现,可以快速实现api能力,同时也可以与其他web框架集成,以下是一个简单试用参考代码demo.pyfromfaststream.redisimportRedisBrokerfromfaststream.asgiimportAsgiFastStream,get,AsgiResponsefromtypingimportAnyfrompyda......
  • 为什么 Streams API 改变了 Web 开发者的游戏规则
    我们首先解释一下数据是如何通过网络发送的。它不是作为单个连续流发送的;相反,它被分成更小的块。在接收端,消费者或应用程序负责在收到所有数据后以正确的顺序和格式重新组装这些块。对于图像、视频和其他相对较大的数据类型,此过程会自动发生。因此streamsapi提供的是一种无需等......
  • Java Stream流编程入门
    流式编程stream流式编程分为首先转化为stream中间函数的链接最后的终结函数怎么转化为stream单列集合List<String>list=newArrayList<String>();Collections.addAll(list,"1","2","3","4","5","6","7","8"......
  • java-----Stream流
    什么是Stream?Stream将要处理的元素集合看作一种流,在流的过程中,借助StreamAPI对流中的元素进行操作,比如:筛选、排序、聚合等Stream流的作用:结合了Lambda表达式,简化集合、数组的操作Stream流的使用步骤:    ①先得到一条Stream流(流水线),并把数据放上去  ......
  • [Java基础]Stream流
    当我第一次阅读Java8中的StreamAPI时,说实话,我非常困惑,因为它的名字听起来与JavaI0框架中的InputStream和OutputStream非常类似。但是实际上,它们完全是不同的东西。Java8Stream使用的是函数式编程模式,如同它的名字一样,它可以被用来对集合进行链状流式的操作。本文......
  • Stream流操作
       准备工作准备Gender枚举类以及Customer类enumGender{MALE("男性"),FEMALE("女性");privateStringvalue;Gender(){}Gender(Stringvalue){this.value=value;}@OverridepublicStringtoString(){......
  • js Stream API简单使用
    ReadableStream<script>//TextDecoder将字节转换为字符串,默认utf-8编码letuint8Array=newUint8Array([72,101,108,108,111]);console.log(newTextDecoder().decode(uint8Array));//Helloletuint8Array1=newUint8Array([228,189,160,229,165......