ストリーム(Stream)の種類
Java8に追加されたjava.util.streamパッケージを見てみましょう。
https://www.developer.com/java/data/stream-operations-supported-by-the-java-streams-api.html
全てのストリームで使用できる共通メソッドは、Base Streamに定義されており、
Streamはオブジェクト要素を処理するストリーム、IntStream、LongStream、DoubleStreamはそれぞれ基本タイプのint、long、double要素を処理するストリームである。
コレクションからストリームを得る
List<String> list = Arrays.asList("あ", "い", "う");
Stream<String> stream = list.stream(); // Collection . stream()
配列からストリームを得る
String[] strArray = {"あ", "い", "う"};
Stream<String> stream = Arrays.stream(strArray);
int[] intArray = {1, 2, 3, 4};
IntStream intStream = Arrays.stream(intArray);
数字の範囲からストリームを取得
IntStream stream = IntStream.rangeClosed(1, 100);
ファイルからストリームを取得
public static void main(String[] args) throws IOException{
Path path = Paths.get("src/stream/list.txt");
Stream<String> stream = Files.lines(path, Charset.defaultCharset());
stream.forEach(System.out :: println);
System.out.println();
File file = path.toFile();
FileReader fileReader = new FileReader(file);
BufferedReader br = new BufferedReader(fileReader);
stream = br.lines();
stream.forEach(System.out :: println);
}
ディレクトリからストリームを取得
public static void main(String[] args) throws IOException{
Path path = Paths.get("c://");
Stream<Path> stream = Files.list(path);
stream.forEach(p -> System.out.println(p.getFileName()));
}