Java8新特性-Stream

本文详细介绍了Java8引入的Stream API,包括如何通过Collection.stream()、Stream.of()和Arrays.stream()创建Stream,以及Stream的中间操作如filter、map、distinct、sorted等和终端操作如forEach、toArray、reduce、collect等。通过实例展示了Stream如何提高代码效率和简洁性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

https://juejin.cn/post/6844903830254010381

Stream简介

Stream 是Java8 新增的API。
Stream将元素集合看作一种流, 流在管道中传输并执行筛选、 排序、聚合等操作最终获得我们想要的结果。
Stream可以极大提高生产力,让Java代码高效、干净、简洁。

一、创建Stream

1. Collection.stream()

Arrays.asList("北京", "上海", "深圳")
                .stream()
                .forEach(System.out :: println);

2. Stream.of()

Stream.of("北京", "上海", "深圳")
                .forEach(System.out :: println);

3. Arrays.stream()

Arrays.stream(new String[]{"北京", "上海", "深圳"})
          .forEach(System.out :: println);

  System.out.println("------------");
  String[] strArr = new String[]{"北京", "上海", "深圳"};
  // 左闭右开
  Arrays.stream(strArr, 0, 2)
          .forEach(System.out :: println);

// 输出
北京
上海
深圳
------------
北京
上海

二、操作Stream

流的操作可以分为两种类型
1)中间操作:可以有多个,每次返回一个新的流,可进行链式操作。
2)终端操作:只能有一个,每次执行完,这个流也就用光了,无法执行下一个操作,因此只能放在最后。
Stream的所有方法

1.中间操作

filter()
map()
mapToInt()
mapToLong()
mapToDouble()
flatMap()
flatMapToInt()
flatMapToLong()
flatMapToDouble()
distinct()
sorted()
peek()
limit()
skip()

filter()

从流中筛选出我们想要的元素

map()

将一个流中的元素转化成新的流中的元素

mapToInt()

mapToLong()

mapToDouble()

flatMap()

flatMapToInt()

flatMapToLong()

flatMapToDouble()

distinct()

去重

sorted()

排序

peek()

limit()

skip()

2.终端操作

forEach()
forEachOrdered()
toArray()
reduce()
collect()
min()
max()
count()
anyMatch()
allMatch()
noneMatch()
findFirst()
findAny()

forEach()

forEachOrdered()

toArray()

reduce()

collect()

min()

max()

count()

anyMatch()

allMatch()

noneMatch()

findFirst()

findAny()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值