流式编程
2020-04-09 本文已影响0人
逢栲怭過
创建流8种方法
1.创建空流 这个方法经常被用在创建一个不含元素的空的流进行返回,避免返回null
private static <T>Stream createEmptyStream(T t){
Stream<T> stream = Stream.empty();
return stream;
}
2.从集合中创建流
private static Stream createCollectionStream(){
Collection<String> collection = Arrays.asList("JAVA", "J2EE", "Spring", "Hibernate");
return collection.stream();
}
3.从数组中创建流
private static Stream createArrayStream(){
// 数组作为Stream源
Stream<String> streamOfArray = Stream.of("a", "b", "c");
streamOfArray.forEach(System.out::println);
// 从数组或者数组的部分元素中创建流
String[] arr = new String[] { "a", "b", "c" };
Stream<String> streamOfArrayFull = Arrays.stream(arr);
return null;
}
4.Stream.builder()创建流
private static Stream createBuilderStream(){
Stream<String> streamBuilder = Stream.<String>builder().add("a").add("b").add("c").build();
streamBuilder.forEach(System.out::println);
return null;
}
5.使用Stream.generate()
private static Stream createGenerateStream(){
Stream<String> streamGenerated = Stream.generate(() -> "element1").limit(10);
streamGenerated.forEach(System.out::println);
return null;
}
6.使用Stream.iterate()
private static Stream createIterateStream(){
Stream<Integer> streamIterated = Stream.iterate(1, n -> n + 2).limit(5);
streamIterated.forEach(System.out::println);
return null;
}
7.文件获取流
public static Stream<String> createFileStream() throws IOException {
Path path = Paths.get("D:\\data\\test.txt");
Stream<String> streamOfStrings = Files.lines(path);
Stream<String> 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<String> createRegexStream() throws IOException {
Path path = Paths.get("D:\\data\\test.txt");
String streamOfStrings = Files.lines(path).collect(Collectors.joining(""));
Stream<String> stringStream= compile("[.]+}").splitAsStream(streamOfStrings);
// Stream<String> streamWithCharset = Files.lines(path, Charset.forName("UTF-8"));
// stringStream.forEach(System.out::println);
return stringStream;
}