Streams
Creating Streams
Copyright © Seán Kennedy
Creating a Stream from an Array
• Arrays.stream() can be used to stream an array.
Copyright © Seán Kennedy
Creating a Stream from a Collection
• The default Collection interface method stream() is used.
Copyright © Seán Kennedy
Creating a Stream with Stream.of()
• Stream.of() is a static generically-typed utility method that
accepts a varargs parameter and returns an ordered stream of
those values.
Copyright © Seán Kennedy
Creating a Stream from a File
• The Files.lines() method can be used to stream a file. It
provides one line at a time from the file as a data element in
the stream.
• To process the data from the stream, we use the Stream
interfaces’ forEach() method, which is a terminal operation.
• Similar to the forEach() for collections, it takes a
Consumer, which enables us to process each line from the
file.
5
Copyright © Seán Kennedy
Creating a Stream from a File
Copyright © Seán Kennedy
Cats.txt
Output
Note that inside the lambda expression, variables from the enclosing scope are either final or effectively final.
This means that while we can add elements to ‘cats’ we cannot change what ‘cats’ refers to i.e. we cannot say
cats=new ArrayList<>();
7
Copyright © Seán Kennedy
Infinite Streams
• Infinite streams can be created in the following ways:
1 of 2
Copyright © Seán Kennedy
Infinite Streams
2 of 2
Copyright © Seán Kennedy
Infinite Streams
• Infinite streams can be turned into finite streams with
operations such as limit(long) :
10
Copyright © Seán Kennedy