1
0

More than 3 years have passed since last update.

[JAVA] ストリーム(Stream)の種類

Posted at

ストリーム(Stream)の種類

Java8に追加されたjava.util.streamパッケージを見てみましょう。
https://www.developer.com/java/data/stream-operations-supported-by-the-java-streams-api.html

1.png

全てのストリームで使用できる共通メソッドは、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()));
}
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0