Streams API
The Streams API creates a sequence of items and iterates through data collections by collapsing iterations into more efficient and readable code.
There are multiple ways to create a stream instance from a collection type and once created, the instance will not modify it’s source, enabling the creation of multiple instances from a single data source.
Create an empty stream
The empty() method is used when creating an empty stream to avoid returning null on a stream that has no elements.
Stream<String> emptyStream = Stream.empty();
Create a stream
Stream<String> groceries = Stream.of("apples","bananas","coffee","milk");
Create a stream from other collection types
Arrays
String[] groceries = new String[] {
"apples",
"bananas",
"coffee",
"milk"
};
Stream<String> groceryStream = Arrays.stream(groceries);
Lists
List<String> groceryList = List.of("apples","bananas","coffee","milk");
Stream<String> groceryListStream = groceryList.stream();
//print the list sequentially
groceryList.stream().forEach(System.out::println);
//print the list in parallel
groceryList.parallelstream().forEach(System.out::println);
//Using lambdas to print each element in the stream
//sequential stream
shoppingList.stream().forEach(s -> System.out.println(s));
//parallel stream
shoppingList.parallelStream().forEach(s -> System.out.println(s));
//Match
//Using a predicate, we can check if all, none, or any of the elements in the stream match a given condition.
boolean anyMatch = shoppingList.stream().anyMatch(s -> s.equals("Apple"));
//Filter
//Create a new stream with only the elements that match a given condition.
Stream<String> itemInAisle = shoppingList.stream()
.filter(item -> item.startsWith("A"));
//Map
//Create a new stream with the results of applying a function to all elements of the stream.
Stream<String> upperCaseStream = shoppingList.stream()
.map(item -> item.toUpperCase());
//Map
//Create a new stream with the results of applying a function to all elements of the stream.
List<Integer> numbers = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
Stream<Integer> doubleStream = numbers.stream()
.map(n -> n +n );
//Collect the elements of the stream into a collection.
List<Integer> doubledList = numbers.stream()
.map(n -> n * 2 )
.collect(Collectors.toList());
The .stream().forEach() replaces a for loop in a single line of code and is used to perform an action on each element in the stream.
takeWhile() & doWhile()
//takeWhile
//Create a new stream with the elements that match a given condition.
Stream<Integer> takeWhileStream = numbers.stream()
.takeWhile(n -> n < 5);
//dropWhile
//Create a new stream with the elements that don't match a given condition.
Stream<Integer> dropWhileStream = numbers.stream()
.dropWhile(n -> n < 5);

