Java Stream 高效开发!16 个案例,让你秒速起飞!

30 阅读3分钟

点击上方“程序员蜗牛g”,选择“设为星标”跟蜗牛哥一起,每天进步一点点程序员蜗牛g大厂程序员一枚 跟蜗牛一起 每天进步一点点31篇原创内容**公众号

我们会通过16个案例详细的讲解有关Stream函数的应用。

实战案例

1.1 查找所有的偶数并求和

public static void p1() {  List<Integer> numbers = Arrays.asList(12345678910);  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(12345);  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(105251530);  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.02.03.04.05.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(246810);  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(246810);  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(246810) ;  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(12345) ;  List<Integer> list2 = Arrays.asList(4567,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亿个数的求和

publicstaticvoidmain(String[] args) {double[] arr = IntStream.range(0100_000_000)      .mapToDouble(i -> new Random().nextDouble() * 100000)      .toArray() ;  computeSumOfSquareRoots(arr);}
publicstaticvoidcomputeSumOfSquareRoots(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);}
publicstaticdoublecomputeSerialSum(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;}
publicstaticdoublecomputeParallelSum(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 Time73 msSerialSum5.000114159154823E12ParallelComputation Time38 msParallelSum5.000114159151367E12

如果这篇文章对您有所帮助,或者有所启发的话,求一键三连:点赞、转发、在看。

关注公众号:woniuxgg,在公众号中回复:笔记  就可以获得蜗牛为你精心准备的java实战语雀笔记,回复面试、开发手册、有超赞的粉丝福利!