当前位置: 首页 > news >正文

stream使用案例

1.1 查找所有的偶数并求和

public static void p1() {  List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);  int sum = numbers.stream()      .filter(num -> num % 2 == 0)      .mapToInt(Integer::intValue)      .sum() ;  System.err.printf("result: %s%n", sum) ;}

1.2 查找并打印长度大于 5 的字符串个数

public static void p2() {  List<String> strings = Arrays.asList(    "apple", "banana", "grape",     "watermelon", "kiwi", "orange");  Long count = strings.stream()      .filter(str -> str.length() > 5)      .count() ;  System.err.printf("result: %s%n", count) ;}

1.3 处理每一个元素最后返回新集合​​​​​​​

public static void p3() {  List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);  List<Integer> squares = numbers.stream()      .map(num -> num * num)      .collect(Collectors.toList()) ;  System.err.printf("result: %s%n", squares) ;}

将每一个元素进行平方操作,最后返回一个新的集合。输出结果:

result: [1, 4, 9, 16, 25]

1.4 找出整数列表中的最大元素​​​​​​​

public static void p4() {  List<Integer> numbers = Arrays.asList(10, 5, 25, 15, 30);  int max = numbers.stream()      .mapToInt(Integer::intValue)      .max()      .getAsInt();  System.err.printf("result: %s%n", max) ;}

1.5 将列表中的所有字符串连接成一个字符串​​​​​​​

public static void p5() {  List<String> fruits = Arrays.asList("apple", "banana", "cherry","coconut", "apple");  String concat =fruits.stream()      .collect(Collectors.joining()) ;  System.err.printf("result: %s%n", concat) ;}

1.6 转成大写再排序​​​​​​​

public static void p6() {  List<String> fruits = Arrays.asList("apple", "Banana", "Grape", "orange", "kiwi");  List<String> sortedUppercase = fruits.stream()      .map(String::toUpperCase)      .sorted()      .collect(Collectors.toList());  System.err.printf("result: %s%n", sortedUppercase) ;}

先将字符串转为大写,然后在进行排序,输出结果:

result: [APPLE, BANANA, GRAPE, KIWI, ORANGE]

1.7 计算double类型平均值​​​​​​​

public static void p7() {  List<Double> doubles = Arrays.asList(1.0, 2.0, 3.0, 4.0, 5.0);  double average = doubles.stream()      .mapToDouble(Double::doubleValue)      .average()      .getAsDouble() ;  System.err.printf("result: %s%n", average) ;}

1.8 删除重复元素​​​​​​​

public static void p8() {  List<String> words = Arrays.asList("apple", "banana", "apple", "orange", "banana", "kiwi");  List<String> uniqueWords = words.stream()      .distinct()      .collect(Collectors.toList()) ;  System.err.printf("result: %s%n", uniqueWords) ;}

1.9 检查所有元素是否符合条件​​​​​​​

public static void p9() {  List<Integer> numbers = Arrays.asList(2, 4, 6, 8, 10);  boolean allEven = numbers.stream()      .allMatch(n -> n%2 == 0) ;  System.err.printf("result: %s%n", allEven) ;}

1.10 检查集合中是否包含特定元素​​​​​​​

public static void p10() {  List<Integer> numbers = Arrays.asList(2, 4, 6, 8, 10);  boolean exists = numbers.stream()      .anyMatch(n -> n.equals(8)) ;  System.err.printf("result: %s%n", exists) ;}

1.11 查找流中最长的字符串​​​​​​​

public static void p11() {  List<String> fruits = Arrays.asList("apple", "banana", "cherry", "coconut", "apple") ;  int max = fruits.stream()    .mapToInt(String::length)    .max()    .getAsInt() ;  System.err.printf("result: %s%n", max) ;}

1.12 从流中删除null值​​​​​​​

public static void p12() {  List<String> fruits = Arrays.asList("apple", "banana", "cherry", null,"coconut", "apple");  List<String> nonNullValues = fruits.stream()      .filter(Objects::nonNull)      .collect(Collectors.toList()) ;  System.err.printf("result: %s%n", nonNullValues) ;}

过滤为null的值,输出结果:

result: [apple, banana, cherry, coconut, apple]

1.13 分组并查找最大值​​​​​​​

public static void p13() {  List<Employee> employees =new ArrayList<>() ;  employees.add(new Employee("Alice","HR",50000.0)) ;  employees.add(new Employee("Bob","IT",60000.0)) ;  employees.add(new Employee("Charlie","Finance",55000.0)) ;  employees.add(new Employee("David","IT",70000.0)) ;  employees.add(new Employee("Eva", "HR", 45000.0)) ;  employees.add(new Employee("Frank","Finance",58000.0));  Map<String, Optional<Employee>> highestSalaryPerDept = employees.stream()      .collect(Collectors.groupingBy(          Employee::getDepartment,           Collectors.maxBy(Comparator.comparingDouble(Employee::getSalary))      ));  highestSalaryPerDept.forEach((key, value) -> {    System.err.printf("部门: %s, \t最高薪: %s%n", key, value.get()) ;  });}

输出结果:

图片

2.14 查找列表中第二小的元素​​​​​​​

public static void p14() {  List<Integer> numbers = Arrays.asList(2, 4, 6, 8, 10) ;  Optional<Integer> secondSmallest = numbers.stream()      .distinct()      .sorted()      .skip(1)      .findFirst() ;  System.err.printf("result: %s%n", secondSmallest) ;}

1.15 查找两个列表的交集​​​​​​​

public static void p15() {  List<Integer> list1 = Arrays.asList(1, 2, 3, 4, 5) ;  List<Integer> list2 = Arrays.asList(4, 5, 6, 7,8) ;  List<Integer> intersection = list1.stream()      .filter(list2::contains)      .collect(Collectors.toList()) ;  System.err.printf("result: %s%n", intersection) ;}

1.16 并行处理提升性能

使用并行流可以通过BaseStream.parallel或Collection#parallelStream操作,如下计算1亿个数的求和​​​​​​​

public static void main(String[] args) {double[] arr = IntStream.range(0, 100_000_000)      .mapToDouble(i -> new Random().nextDouble() * 100000)      .toArray() ;  computeSumOfSquareRoots(arr);}
public static void computeSumOfSquareRoots(double[] arr) {double serialSum = computeSerialSum(DoubleStream.of(arr));  System.out.println("Serial Sum: " + serialSum);
double parallelSum = computeParallelSum(DoubleStream.of(arr));  System.out.println("Parallel Sum: " + parallelSum);}
public static double computeSerialSum(DoubleStream stream) {long startTime = System.currentTimeMillis();double sum = stream.reduce(0.0D, (l, r) -> l + r) ;long endTime = System.currentTimeMillis();  System.out.println("Serial Computation Time: " + (endTime - startTime) + " ms");return sum;}
public static double computeParallelSum(DoubleStream stream) {long startTime = System.currentTimeMillis();double sum = stream.parallel().reduce(0, (l, r) -> l + r) ;long endTime = System.currentTimeMillis();  System.out.println("Parallel Computation Time: " + (endTime - startTime) + " ms");return sum;}

运行结果​​​​​​​

SerialComputation Time: 73 msSerialSum: 5.000114159154823E12ParallelComputation Time: 38 msParallelSum: 5.000114159151367E12

相关文章:

  • 代码随想录算法训练营day18
  • 什么是 Paxos和Raft
  • 信号处理学习——文献精读与code复现之TFN——嵌入时频变换的可解释神经网络(下)
  • 商业秘密中经营信息的法律保护探析——以客户名册为例
  • 开源3D 动态银河系特效:Vue 与 THREE.JS 的奇幻之旅
  • 如何在FastAPI中打造坚不可摧的Web安全防线?
  • Java 编程之观察者模式详解
  • 笔记05:Allegro导入DXF文件
  • Tailwind CSS工作原理
  • Harbor的安装与使用
  • C++ 第三阶段 新标准库组件 - 第二节:std::filesystem(文件系统操作)
  • 设计模式-代理模式、装饰者模式
  • Vue3—插槽solt
  • 微机系统 - 第7章 -可编程接口芯片
  • 概率概率密度
  • GO 语言学习 之 函数
  • 基于MFC的遥感图像匹配程序设计
  • 前端进阶之路-从传统前端到VUE-JS(第一期-VUE-JS环境配置)(Node-JS环境配置)(Node-JS/npm换源)
  • SQL 子查询全位置解析:可编写子查询的 7 大子句
  • Hyper-v-中的FnOs--飞牛Nas虚拟磁盘扩容(不清除数据)