2024-03-28 Java8之Stream流常用方法

发布于:2024-03-28 ⋅ 阅读:(14) ⋅ 点赞:(0)

Stream流对象常用操作

1.Stream对象创建

1.流对象创建(Stream)

<T> Stream<T> of(T... values)
Stream<Integer> stream = Stream.of(1,2,3,4,5);

2.集合创建(Collection)

Stream<E> stream(); //串行流
Stream<E> parallelStream();//并行流
Stream<String> stream = new ArrayList<>().stream();  //串行流
Stream<String> parallel = new ArrayList<>().parallelStream(); //并行流
Stream<Integer> parallel = new ArrayList<>().stream().parallel();//并行流

3.数组创建(Arrays)

<T> Stream<T> stream(T[] array); 
String[] temp =  {"111","222"};
Stream<String> stream = Arrays.stream(temp);

2.中间操作(返回值为流对象)

Stream<R> map(Function<? super T, ? extends R> mapper); //遍历
IntStream mapToInt(ToIntFunction<? super T> mapper); //遍历转int返回IntStream流
LongStream mapToLong(ToLongFunction<? super T> mapper); //遍历转double流
DoubleStream mapToDouble(ToDoubleFunction<? super T> mapper); //遍历转long流    
//注意:mapToInt等方法返回的流对象,可直接接sum、max等方法,也可接reduce方法,而map后返回的是对象只能接reduce    
Stream<T> filter(Predicate<? super T> predicate);  //过滤
Stream<T> distinct(); //去重
Stream<T> sorted(); //排序
Stream<T> limit(long maxSize); //截取前maxSize个元素,返回一个新的Stream对象
//扁平操作,可以将生成的新流收集起来作为一个新的流,flatMap()操作具有对流的元素应用一对多变换
//然后将所得到的元素平坦化为新流的效果
//通俗来说就是flatMap()可以将map遍历时候中间产生的新的流合并为一个流,然后对新流进行操作,而原本的map操作为一对一
//比如集合map遍历时候里面有一个子集合,将子集合转换为流对象后,map无法将每个子集合的流对象合并,而flatMap就可以合并为新流操作
<R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper);
IntStream flatMapToInt(Function<? super T, ? extends IntStream> mapper); //参考map和mapToInt
LongStream flatMapToLong(Function<? super T, ? extends LongStream> mapper);
DoubleStream flatMapToDouble(Function<? super T, ? extends DoubleStream> mapper);

1.遍历处理集合将结果收集为新集合

List<String> strList = list.stream().map(DemoObj::getCode).limit(5).distinct().collect(Collectors.toList()); //遍历截取前五个去重

2.遍历处理集合筛选满足条件数据收集为新集合

List<String> strList = list.stream().filter(item -> "xxx".equals(item.getCode())).collect(Collectors.toList());

3.将集合列表某个字段用指定字符分隔连接

String str = list.stream().map(DemoObj::getCode).collect(Collectors.joining(","));//遍历list集合取将DemoObj对象的code属性用逗号拼接

4.转换遍历求和

int strList = list.stream().mapToInt(DemoObj::getAmount).reduce(0,Integer::sum);//转int流进行求和

5.flatMap操作

public class Test {
    public static void main(String[] args) {
        List<DemoObj> list = new ArrayList<>();
       list.add(new DemoObj("111",11));
       list.add(new DemoObj("222",22));

       //flatMap合并为新流
       list.stream().flatMap(item ->{
           List<DemoObj> list2 = new ArrayList<>();
            list2.add(item);
            return list2.stream();
       }).forEach(e ->System.out.println("flatMap===="+e));


       //map返回的还是流对象,遍历出来也是单个的流对象
       list.stream().map(item ->{
           List<DemoObj> list2 = new ArrayList<>();
            list2.add(item);
            return list2.stream();
       }).forEach(e ->System.out.println("map===="+e));

    }

    static class  DemoObj{
        private String code;
        private Integer amount;

        public DemoObj(String code, Integer amount) {
            this.code = code;
            this.amount = amount;
        }

        @Override
        public String toString() {
            return "DemoObj{" +
                    "code='" + code + '\'' +
                    ", amount=" + amount +
                    '}';
        }
    }
}

3.终值操作

1.收集(collect)

R collect(Collector<? super T, A, R> collector); //收集
List<String> strList = list.stream().map(DemoObj::getCode).collect(Collectors.toList());//遍历

2.判断元素(anyMatch、allMatch、noneMatch)

boolean anyMatch(Predicate<? super T> predicate); //是否存在
boolean allMatch(Predicate<? super T> predicate); //都存在
boolean noneMatch(Predicate<? super T> predicate); //都不存在
boolean flag = list.stream().anyMatch(item -> "xxx".equals(item.getCode()));//查询集合是否有某个元素
boolean flag = list.stream().allMatch(item -> "xxx".equals(item.getCode())); //查询集合是否都符合
boolean flag = list.stream().noneMatch(item -> "xxx".equals(item.getCode()));//查询集合是否没有指定元素

3.获取元素(findFirst、findAny)

Optional<T> findFirst(); //第一个元素
Optional<T> findAny(); //任意元素
Optional<DemoObj> first = list.stream().filter(item -> "xxx".equals(item.getCode())).findFirst(); //第一个数据
Optional<DemoObj> any = list.stream().filter(item -> "xxx".equals(item.getCode())).findAny(); //任意数据

4.结果计算(count、sum、reduce)

long count(); //统计
int sum();//求和 该方法是IntStream方法
T reduce(T identity, BinaryOperator<T> accumulator); //归并操作
reduce(0,(a,b)->a+b)  //0为初始值  ab为上个操作返回值  a+b为计算规则
BigDecimal amount = list.stream().map(DemoObj::getMoney).reduce(BigDecimal.ZERO, BigDecimal::add);//求和
int strList = list.stream().mapToInt(DemoObj::getAmount).reduce(0,Integer::sum);//转int流进行求和
int strList = list.stream().mapToInt(DemoObj::getAmount).reduce(0,(a,b)->a+b);//效果同上
int strList = list.stream().mapToInt(DemoObj::getAmount).sum();//转int流进行求和
int count = list.stream().mapToInt(DemoObj::getAmount).count();//求个数

5.求最值(max、min)

Optional<T> min(Comparator<? super T> comparator); //最小值
Optional<T> max(Comparator<? super T> comparator); //最大值
 //需要比较器,而mapToInt等方法无需比较器
 DemoObj demoObj = list.stream().max(Comparator.comparing(DemoObj::getAmount)).get();//求最大值数据 
 DemoObj demoObj = list.stream().min(Comparator.comparing(DemoObj::getAmount)).get();//求最小值数据
 int amount = list.stream().mapToInt(DemoObj::getAmount).max();//最大值
本文含有隐藏内容,请 开通VIP 后查看