0% found this document useful (0 votes)
2 views

Creating Streams

The document provides an overview of creating streams in Java, detailing methods such as Arrays.stream(), Collection.stream(), Stream.of(), and Files.lines() for different data sources. It also discusses the processing of stream data using the forEach() method and introduces the concept of infinite streams, which can be limited to finite streams using the limit() operation. Additionally, it highlights the importance of variable scope in lambda expressions.

Uploaded by

srrm.nnn
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Creating Streams

The document provides an overview of creating streams in Java, detailing methods such as Arrays.stream(), Collection.stream(), Stream.of(), and Files.lines() for different data sources. It also discusses the processing of stream data using the forEach() method and introduces the concept of infinite streams, which can be limited to finite streams using the limit() operation. Additionally, it highlights the importance of variable scope in lambda expressions.

Uploaded by

srrm.nnn
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

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

You might also like