JUC_04

Stream流式计算
大数据:存储+计算
集合mysql是用来存储的
流来进行计算
链式编程

点击查看代码
package org.li;

import org.li.pojo.Books;

import java.util.Arrays;
import java.util.List;

public class StreamDemo {
    public static void main(String[] args) {
        Books books1 =new Books(1,"java",10);
        Books books2 =new Books(2,"c",22);
        Books books3 =new Books(3,"cs",23);
        Books books4 =new Books(4,"cpp",24);
        Books books6 =new Books(6,"php",26);
        List<Books> list = Arrays.asList(books1,books2,books3,books4,books6);
        list.stream().filter((u)->{
           return  u.getId()%2==0;
        }).filter((u)->{
            return u.getNums()>23;
                })
                .map((u)->{
                    return u.getName().toUpperCase();
                })
                .sorted((u1,u2)->{
                    return u2.compareTo(u1);
                }).limit(1)
          .forEach(System.out::println);
    }
}

Java Stream流方法全解析
以下是基于Java 8+ Stream API的核心方法分类与说明,结合主流开发实践综合整理:

一、‌Stream创建方法‌
‌集合转Stream‌

java
Copy Code
List list = Arrays.asList(1,2,3);
Stream stream = list.stream(); // 通过集合接口创建‌:ml-citation{ref="2,8" data="citationList"}
‌数组转Stream‌

java
Copy Code
String[] arr = {"a", "b", "c"};
Stream stream = Arrays.stream(arr); // 支持数组类型‌:ml-citation{ref="2,8" data="citationList"}
‌静态方法Stream.of()‌

java
Copy Code
Stream stream = Stream.of("A", "B", "C"); // 直接生成流‌:ml-citation{ref="2,8" data="citationList"}
二、‌中间操作方法‌(返回新Stream,可链式调用)
‌过滤与去重‌

filter(Predicate):条件过滤(如student -> age > 15)‌18
distinct():基于equals()去重(如去重相同对象)‌17
‌转换与映射‌

map(Function<T, R>):元素类型转换(如Student::getName提取名称)‌28
mapToInt(ToIntFunction):转为数值流(如Integer::intValue优化计算)‌48
‌限制与跳过‌

limit(long n):保留前n个元素‌28
skip(long n):跳过前n个元素‌28
‌排序与去重规则‌

sorted():自然顺序排序‌78
sorted(Comparator):自定义排序(如Comparator.comparing(Student::getAge))‌78
三、‌终止操作方法‌(触发计算并关闭流)
‌聚合与统计‌

count():统计元素数量‌68
sum():数值流求和(需配合mapToInt等)‌48
min()/max():获取极值(需Comparator或自然顺序)‌8
‌遍历与收集‌

forEach(Consumer):遍历元素(如System.out::println)‌8
collect(Collector<T, A, R>):转换为集合(如Collectors.toList())‌28
‌匹配与查找‌

anyMatch(Predicate):是否存在满足条件的元素‌8
findFirst():返回第一个元素(返回Optional)‌8
‌归约操作‌

reduce(BinaryOperator):累积计算(如累加、字符串拼接)‌8
四、‌典型应用示例‌
java
Copy Code
// 多条件过滤并收集为List
List filtered = studentList.stream()
.filter(s -> s.getAge() > 15 && "10".equals(s.getClassName()))
.collect(Collectors.toList()); //‌:ml-citation{ref="1,2" data="citationList"}

// 数值流求和
int total = numbers.stream()
.mapToInt(Integer::intValue)
.sum(); //‌:ml-citation{ref="4,8" data="citationList"}

// 去重后排序
List sortedDistinct = numbers.stream()
.distinct()
.sorted()
.collect(Collectors.toList()); //‌:ml-citation{ref="7,8" data="citationList"}
五、‌注意事项‌
‌流不可复用‌:终止操作后流会关闭,再次使用会抛出IllegalStateException‌28
‌性能优化‌:
优先使用基本类型特化流(如IntStream)减少装箱开销‌48
避免在流中执行复杂阻塞操作(如I/O)‌2
‌并行流慎用‌:数据量大的场景可用parallelStream(),但需确保线程安全‌28

posted @ 2025-04-17 14:00  黑影五  阅读(59)  评论(0)    收藏  举报