Java Stream流中的实用操作,各种流操作的参考示例分析

本文详细介绍了Java Stream流的各种实用操作,包括求和、最大值、最小值、计数、匹配、收集器以及并行处理等。通过具体的代码示例,展示了如何使用Stream API进行高效的数据处理和分析。
摘要由CSDN通过智能技术生成
  • sum: 对Stream流元素进行求和

List list = Arrays.asList(1, 2, 3, 4, 5, 6);

// 求集合的最大值 - 6

System.out.println(list.stream().max((a, b) -> a - b).get());

// 求集合的最小值 - 1

System.out.println(list.stream().min((a, b) -> a - b).get());

// 统计元素的个数 - 6

System.out.println(list.stream().count());

// 元素求和

String str = “11, 22, 33, 44, 55”;

System.out.println(Stream.of(str.split(“,”)).mapToInt(x -> Integer.valueOf(x)).sum());

System.out.println(Stream.of(str.split(“,”)).mapToInt(Integer :: valueOf).sum());

System.out.println(Stream.of(str.split(“,”)).map(x -> Integer.valueOf(x)).mapToInt(x -> x).sum());

System.out.println(Stream.of(str.split(“,”)).map(Integer :: valueOf).mapToInt(x -> x).sum());

匹配-anyMatch,allMatch,noneMatch,findFirst,findAny

================================================

  • anyMatch: 接收一个Predicate函数,只要Stream流中有一个元素满足该断言则返回true, 否则返回false

  • allMatch: 接收一个Predicate函数,当Stream流中每一个元素都满足该断言则返回true, 否则返回false

  • noneMatch: 接收一个Predicate函数,当Stream流中每一个元素都不符合该断言则返回true, 否则返回false

  • findFirst: 返回Stream流中的第一个元素

  • findAny: 返回Stream流中的任意一个元素

List list = Arrays.asList(1, 2, 3, 4, 5, 6);

// 如果集合的元素都大于等于0则返回true

System.out.println(list.stream().allMatch(x -> x >= 0));

// 如果集合中有大于5的元素,返回false

Systemm.out.println(list.stream().noneMatch(x -> x > 5));

// 如果集合中有大于3的元素则返回true

System.out.println(list.stream().anyMatch(x -> x > 3));

// 取第一个偶数

System.out.println(list.stream().filter(x -> x % 2 == 0).findFirst().get());

// 取任意一个偶数

System.out.println(list.stream().filter(x -> x % 2 == 0).findAny().get());

收集器-toArray,collect

===================

  • collect: 接收一个Collector实例,将流中元素转变为另外一种数据结构

  • Collector<T, A, R> 是一个接口,包含5个抽象方法: Supplier< A > supplier(): 创建一个结果容器 BiConsumer<A, T> accumulator(): 消费型接口. 第一个参数为容器A, 第二个参数为流中元素T BinaryOperator< A > combiner(): 函数接口. 该函数的作用是将各个子流程的运行结果,即accumulator函数操作后的容器A进行合并 Function<A, R> finisher(): 函数式接口. 参数为容器A, 返回类型为collect方法需要的结果类型R Set< Chracteristics > characteristics(): 返回一个不可变的Set集合,用来表明该Collector的特性

// 将对象值转化为List

List ageList = userList.stream().map(User :: getAge).collect(Collectors.toList());

// 将对象值转化为Set

Set ageSet = userList.stream().map(User :: getAge).collect(Collectors.toMap());

// 将对象值转换为Map. 要求key的取值不能相同

Map<String, Integer> userMap = userList.stream().collect(Colletors.toMap(User :: getName, User :: getAge));

// 字符串分隔符连接

String joinName = userList.stream().map(User :: getName).collect(Collectors.join(“,”, “(”, “)”))

// 聚合操作 - 计算对象总数

Long count = userList.stream().collect(Collectors.counting());

// 聚合操作 - 计算最大值

Integer maxAge = userList.stream().map(User :: getAge).collect(Collectors.maxBy(Integer :: compare)).get();

// 聚合操作 - 计算对象值总数

Integer sumAge = userList.stream().collect(Collectors.summingInt(User :: getAge));

// 聚合操作 - 计算对象值的平均数

Double averageAge = userList.stream().collet(Collectors.averagingDouble(User :: getAge));

// 根据Age分组

Map<Integer, List> ageMap = userList.stream().collect(Collectors.groupingBy(User :: getAge));

// 根据条件分区: 一部分大于10, 一部分小于10

Map<Boolean, List> partMap = userList.stream().collect(Collectors.partitionBy(x -> x.getAge() > 10));

// 规约

Integer value = userList.stream().map(User :: getAge).collect(Collectors.reducing(Integer :: sum)).get();

parallelStream

==============

  • parallelStream是流并行处理程序的代替方法

List strings = Arrays.asList(“I”, “want”, “to”, “be”, “”, “great”);

long count = strings.parallelStream().filter(string -> string.isEmpty()).count();

  • 可以很容易的在顺序运行和并行之间进行直接切换

Collectors

==========

  • Collectors类实现很多归约操作,比如将流转换成集合和聚合元素

  • Collectors可用于返回列表和字符串

List strings = Arrays.asList(“I”, “want”, “to”, “be”, “”, “great”);

// 过滤掉空字符串

List filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList());

// 合并字符串

String mergedString = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.joining(“,”));

averagingDouble

===============

/**

  • 返回一个Collector,生成应用于输入元素double值函数的算术平均值

  • 结果可能会存在误差

  • @param mapper 获取需要计算算数平均值的值的映射器

  • @return Collector<T, ?, Double> 计算算术平均值的Collector

*/

public static Collector<T, ?, Double> averagingDouble(ToDoubleFunction<? super T> mapper) {

/*

  • 在收集操作的数组中:

  • 索引0 - 运行总和的高位

  • 索引1 - 补偿计算总和的低位

  • 索引2 - 可见值的数量

*/

return new CollectorImpl<>(

() -> new double[4],

(a, t) -> { double val = mapper.applyAsDouble(t); sumWithCompensation(a, val); a[2]++; a[3]+= val;},

(a, b) -> { sumWithCompensation(a, b[0]); sumWithCompensation(a, b[1]); a[2] += b[2]; a[3] += b[3]; return a; },

a -> (a[2] == 0) ? 0.0d : (computeFinalSum

  • 8
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值