Input/Output and Streams in Java
Alex Liu
Software Development Engineer
Java Streams
ArrayList
, LinkedList
)HashSet
, TreeSet
)Keys
/Values
as Streams
) (e.g., HashMap
, TreeMap
)Arrays.stream()
)Example ArrayList
named names
to use for the rest of the video
names: ["Alice", "Bob", "Charlie", "David"]
(parameters) -> { expression }
names.forEach(
// `name` is a parameter representing each element in the list
name ->
// This is the expression executed for each element.
System.out.println(name));
Alice
Bob
Charlie
David
Convert data collection to Stream
.stream()
on a collectionList
, Set
and Queue
Import Stream
class
import java.util.stream.Stream;
names
to streams and use .foreach()
to access each element.Stream<String> stream = names.stream();
stream.forEach(name -> System.out.println(name));
.filter()
to select elementsnames
to streamsStream<String> stream = names.stream();
.filter()
to match elements starts with A
and use .forEach()
to print themstream
.filter(name -> name.startsWith("A"))
.forEach(name -> System.out.println(name));
Alice
Use .count()
to count elements
long
formatConverted sample list names
to streams
Stream<String> stream = names.stream();
Use .filter()
to match elements starts with B
and use .count()
to count them
long count = names.stream()
.filter(name -> name.startsWith("B"))
.count();
Count result: 1 (only 1 element Bob
start with B
)
Streams
:Streams
:Input/Output and Streams in Java