Stream是Java8的重要特性之一。那么生成Stream的方式有哪些? 1, 通过Collections类,2,通过静态方法,例如IntStream.range,Files.walk方法等, 3,借助Java.util.Spliterator,有关stream的更详细内容后面会介绍,这里只是简单给出生成stream的例子。
下面通过代码示例一一展示。
第一种,通过Collections类
List<String> stringCollection = new ArrayList<>();
stringCollection.add("ddd2");
stringCollection.add("aaa2");
stringCollection.add("bbb1");
stringCollection.add("aaa1");
stringCollection.add("bbb3");
stringCollection.add("ccc4");
stringCollection.add("bbb2");
stringCollection.add("ddd1");
stringCollection
.stream()
.filter((s) -> s.startsWith("a"))
.forEach(System.out::println);
第二种,通过静态方法
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;
import java.io.IOException;
public class FilesWalk {
public static void main(String[] args) {
final Path path = Paths.get("C:\\Afolder");
int maxDepth = 5;
try( Stream<Path> entries = Files.walk(path, maxDepth) ) {
entries.onClose( () -> System.out.println("Done!") ).forEach(
p -> {
System.out.println(p.toFile().getAbsolutePath());
}
);
}
catch (IOException e) {
e.printStackTrace();
}
}
}
第三种,借助java.util.Spliterator;
import java.util.ArrayList;
import java.util.Spliterator;
import java.util.stream.StreamSupport;
import java.util.stream.Stream;
public class SpliteratorDemo {
public static void main(String[] args) {
ArrayList<Integer> number_List = new ArrayList<>();
Spliterator<Integer> mySpliterator, myParallelSpliterator;
number_List.add(1);
number_List.add(2);
number_List.add(3);
number_List.add(4);
number_List.add(5);
mySpliterator = number_List.spliterator();
myParallelSpliterator = number_List.spliterator();
System.out.println("Characteristics Of Spliterator are : "+mySpliterator.characteristics());
System.out.println("estimateSize Of Spliterator is : "+mySpliterator.estimateSize());
Stream<Integer> intStream = StreamSupport.stream(mySpliterator.trySplit(), false);
Stream<Integer> intStream2 = StreamSupport.stream(mySpliterator.trySplit(), false);
Stream<Integer> intStream3 = StreamSupport.stream(mySpliterator.trySplit(), false);
//Stream<Integer> intStream4 = StreamSupport.stream(mySpliterator.trySplit(), false);
Stream<Integer> intStream4 = StreamSupport.stream(myParallelSpliterator.trySplit(), true);
System.out.println("All elements");
intStream
.filter((p) -> (p < 9))
.forEach(System.out::println);
System.out.println("All elements");
intStream2
.forEach(System.out::println);
System.out.println("All elements");
intStream3
.forEach(System.out::println);
System.out.println("All elements");
intStream4
.forEach(System.out::println);
}
}