创建流8种方法
1.创建空流 这个方法经常被用在创建一个不含元素的空的流进行返回,避免返回null
private static Stream createEmptyStream(T t){
Stream stream = Stream.empty();
return stream;
}
2.从集合中创建流
private static Stream createCollectionStream(){
Collection collection = Arrays.asList("JAVA", "J2EE", "Spring", "Hibernate");
return collection.stream();
}
3.从数组中创建流
private static Stream createArrayStream(){
// 数组作为Stream源
Stream streamOfArray = Stream.of("a", "b", "c");
streamOfArray.forEach(System.out::println);
// 从数组或者数组的部分元素中创建流
String[] arr = new String[] { "a", "b", "c" };
Stream streamOfArrayFull = Arrays.stream(arr);
return null;
}
4.Stream.builder()创建流
private static Stream createBuilderStream(){
Stream streamBuilder = Stream.builder().add("a").add("b").add("c").build();
streamBuilder.forEach(System.out::println);
return null;
}
5.使用Stream.generate()
private static Stream createGenerateStream(){
Stream streamGenerated = Stream.generate(() -> "element1").limit(10);
streamGenerated.forEach(System.out::println);
return null;
}
6.使用Stream.iterate()
private static Stream createIterateStream(){
Stream streamIterated = Stream.iterate(1, n -> n + 2).limit(5);
streamIterated.forEach(System.out::println);
return null;
}
7.文件获取流
public static Stream createFileStream() throws IOException {
Path path = Paths.get("D:\\data\\test.txt");
Stream streamOfStrings = Files.lines(path);
Stream streamWithCharset = Files.lines(path, Charset.forName("UTF-8"));
// streamOfStrings.forEach(System.out::println);
// streamWithCharset.forEach(System.out::println);
// streamOfStrings.close();
// streamWithCharset.close();
return streamWithCharset;
}
8.从数据中获取
private static Stream createCreationStream() throws IOException {
IntStream intStream = IntStream.range(1, 4);
intStream.forEach(System.out::println);
LongStream longStream = LongStream.rangeClosed(1, 5);
longStream.forEach(System.out::println);
Random random = new Random();
DoubleStream doubleStream = random.doubles(2);
doubleStream.forEach(System.out::println);
return null;
}
9.正则表达式生成流
public static Stream createRegexStream() throws IOException {
Path path = Paths.get("D:\\data\\test.txt");
String streamOfStrings = Files.lines(path).collect(Collectors.joining(""));
Stream stringStream= compile("[.]+}").splitAsStream(streamOfStrings);
// Stream streamWithCharset = Files.lines(path, Charset.forName("UTF-8"));
// stringStream.forEach(System.out::println);
return stringStream;
}