stream基础
Stream学习
1. 认识stream
stream是java8中用来表示元素的一种序列,提供了很多方便的操作提高开发效率。
2. 流的创建
- 通过collection创建
List.of("hello", "world").stream().limit(1).forEach(System.out::println);
- 通过Arrays创建
String[] arry = {"java", " ","python", "go", "hello"};
Arrays.stream(arry).forEach(System.out::println);
- 通过stream类中的of方法创建
String[] arry = {"java", " ","python", "go", "hello"};
Stream.of(arry).forEach(System.out::println);
- 创建无限流,通过迭代或生成
Stream.generate(() -> new Random(10)).limit(10).forEach(System.out::println);
Stream.iterate(1, i -> i+1).limit(10).forEach(System.out::println);
3. 流的基本操作
- 中间操作
包含:filter、map、peek、sorted、distinct、flatMap、limit - 终止操作
包含:foreach、collect、reduce、min、max、count、findfirst、findany、anymatch、allmatch、nonematch
public class StreamOpTest {
public static void main(String[] args) {
String[] strArry = {"java","python","","go", "c++_demo","python"};
Arrays.stream(strArry)
.filter(x -> !x.isEmpty())
.distinct()
.sorted()
.limit(1)
.map(i -> i.replace("_", ""))
.flatMap(str -> Stream.of(str.split("")))
.forEach(System.out::println);
}
}

浙公网安备 33010602011771号