Java —— Stream的使用

54 篇文章 1 订阅
本文详细介绍了Java8中的流(Stream)概念,包括顺序流和并行流的创建及使用,如通过Arrays.stream()和Stream.of()等方法。讲解了流的遍历、匹配、筛选、映射、归约、收集等核心操作,并展示了如何进行数据的统计、分组、排序、提取等高级用法。此外,还探讨了如何利用流进行数据的去重、限制数量、跳过指定数量元素等操作。
摘要由CSDN通过智能技术生成

        Stream在Java8中出现,将要处理的元素视作流。

流的种类

顺序流stream主线程按顺序对流执行操作。
并行流parallelStream内部以多线程并行执行的方式对流进行操作,需要流中的数据处理无顺序要求。

流的创建

xxx.stream();
Arrays.stream(xxx);
Stream.of(1, 2, 3, 4, 5, 6);
Stream.iterate(0, (x) -> x + 3).limit(4);
Stream.generate(Math::random).limit(3);

流的遍历

list.stream().forEach(System.out::println);

流的匹配

匹配第一个list.stream().filter(x -> x > 6).findFirst();
匹配任意一个list.stream().filter(x -> x > 6).findAny();
是否包含符合特定条件的元素,结果为布尔值list.stream().anyMatch(x -> x < 6);
计算符合条件的总个数long count = list.stream().filter(x -> x > 6).count();

流的筛选

stream.filter(x -> x > 7).forEach(System.out::println);

流的映射

以函数作为参数,将每个元素映射成新的list.stream().map(x -> x + 3).collect(Collectors.toList())

流的归约

list.stream().reduce((x, y) -> x + y);

流的收集

        流不存储数据,那么在流中的数据完成处理后,需要将流中的数据重新归集到新的集合里。

归集

list.stream().filter(x -> x % 2 == 0).collect(Collectors.toList());
list.stream().filter(x -> x % 2 == 0).collect(Collectors.toSet());

list.stream().collect(Collectors.toMap(ABC::getA, ABC::getB, (x, y) -> x))

第一个参数:key

第二个参数:value

第三个方式:如果待加入的key与现有key产生冲突,如何处理

统计

  • 计数:count
  • 平均值:averagingInt、averagingLong、averagingDouble
  • 最值:maxBy、minBy
  • 求和:summingInt、summingLong、summingDouble
  • 统计以上所有:summarizingInt、summarizingLong、summarizingDouble
list.stream().collect(Collectors.averagingDouble(ABC::getA));
list.stream().map(ABC::getA).collect(Collectors.maxBy(Integer::compare));

分组

partitioningBy

list.stream().collect(Collectors.partitioningBy(x -> x.getA() > 8000));   —— A

groupingBy

list.stream().collect(Collectors.groupingBy(Person::getSex));              —— B
list.stream().collect(Collectors.groupingBy(Person::getSex, Collectors.groupingBy(Person::getArea)));                                           —— C

A

员工按薪资是否大于8000分组情况:

{false=[mutest.Person@2d98a335, mutest.Person@16b98e56, mutest.Person@7ef20235], true=[mutest.Person@27d6c5e0, mutest.Person@4f3f5b24, mutest.Person@15aeb7ab]}

B

员工按性别分组情况:

{female=[mutest.Person@16b98e56, mutest.Person@4f3f5b24, mutest.Person@7ef20235], male=[mutest.Person@27d6c5e0, mutest.Person@2d98a335, mutest.Person@15aeb7ab]}

C

员工按性别、地区:

{female={New York=[mutest.Person@4f3f5b24, mutest.Person@7ef20235], Washington=[mutest.Person@16b98e56]}, male={New York=[mutest.Person@27d6c5e0, mutest.Person@15aeb7ab], Washington=[mutest.Person@2d98a335]}}

 联结

list.stream().map(p -> p.getName()).collect(Collectors.joining(","));

排序

list.stream().sorted(Comparator.comparing(Person::getSalary)).map(Person::getName) .collect(Collectors.toList());

        // 自定义排序

        list.stream().sorted((p1, p2) -> {
            if (p1.getSalary() == p2.getSalary()) {
                return p2.getAge() - p1.getAge();
            } else {
                return p2.getSalary() - p1.getSalary();
            }
        }).map(Person::getName).collect(Collectors.toList());

提取

合并与去重Stream.concat(stream1, stream2).distinct().collect(Collectors.toList());
限制数量Stream.iterate(1, x -> x + 2).limit(10).collect(Collectors.toList());
跳过前n个Stream.iterate(1, x -> x + 2).skip(1).limit(5).collect(Collectors.toList());

Java 8中新增的Stream是一种处理集合的优雅姿势。 Stream是对集合(Collection)对象功能的增强,它能以一种声明的方式来处理数据,实现类似于SQL语句的操作。Stream不会改变原有的数据结构,它会生成一个新的Stream,同时支持并行化操作。 Stream的核心思想是将数据看作是流,而流上可以进行各种操作,比如过滤、排序、映射等。这样可以将数据处理过程变得非常简洁和灵活。 下面是一些Stream的常用操作: 1. filter:过滤符合条件的元素 ``` List<Integer> list = Arrays.asList(1, 2, 3, 4, 5); list.stream().filter(i -> i % 2 == 0).forEach(System.out::println); //输出2, 4 ``` 2. map:将元素转换成另一种类型 ``` List<String> list = Arrays.asList("apple", "banana", "orange"); list.stream().map(s -> s.toUpperCase()).forEach(System.out::println); //输出APPLE, BANANA, ORANGE ``` 3. sorted:对元素进行排序 ``` List<Integer> list = Arrays.asList(5, 2, 1, 4, 3); list.stream().sorted().forEach(System.out::println); //输出1, 2, 3, 4, 5 ``` 4. distinct:去重 ``` List<Integer> list = Arrays.asList(1, 2, 3, 2, 1); list.stream().distinct().forEach(System.out::println); //输出1, 2, 3 ``` 5. limit:限制元素个数 ``` List<Integer> list = Arrays.asList(1, 2, 3, 4, 5); list.stream().limit(3).forEach(System.out::println); //输出1, 2, 3 ``` 6. skip:跳过元素 ``` List<Integer> list = Arrays.asList(1, 2, 3, 4, 5); list.stream().skip(2).forEach(System.out::println); //输出3, 4, 5 ``` 7. reduce:对元素进行聚合操作 ``` List<Integer> list = Arrays.asList(1, 2, 3, 4, 5); int sum = list.stream().reduce(0, (a, b) -> a + b); System.out.println(sum); //输出15 ``` Stream的操作可以组合起来形成一个流水线,每个操作都会返回一个新的Stream对象,这样就可以形成一个操作序列。最后调用终止操作(如forEach、findAny等)才会触发所有中间操作的执行。 使用Stream处理集合的代码通常比使用传统的循环更简洁,同时也更易于并行化处理,提高了程序的效率。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

宇宙超级无敌程序媛

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值