創(chuàng)建流8種方法
1.創(chuàng)建空流 這個方法經(jīng)常被用在創(chuàng)建一個不含元素的空的流進(jìn)行返回,避免返回null
private static <T>Stream createEmptyStream(T t){
Stream<T> stream = Stream.empty();
return stream;
}
2.從集合中創(chuàng)建流
private static Stream createCollectionStream(){
Collection<String> collection = Arrays.asList("JAVA", "J2EE", "Spring", "Hibernate");
return collection.stream();
}
3.從數(shù)組中創(chuàng)建流
private static Stream createArrayStream(){
// 數(shù)組作為Stream源
Stream<String> streamOfArray = Stream.of("a", "b", "c");
streamOfArray.forEach(System.out::println);
// 從數(shù)組或者數(shù)組的部分元素中創(chuàng)建流
String[] arr = new String[] { "a", "b", "c" };
Stream<String> streamOfArrayFull = Arrays.stream(arr);
return null;
}
4.Stream.builder()創(chuàng)建流
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.從數(shù)據(jù)中獲取
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.正則表達(dá)式生成流
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;
}