Java : Diving Deeper into Streams
Just delve deeper into Java Streams because I find them very convenient to use.
What is Stream API?
Stream API is an operation executed on collection, so when we read the code, we can comprehend the code very quickly. It is also called pipelined operation.
.filter()
.skip()
.limit()
.distinct()
.sorted()
.map()
.dropwhile()
.takewhile()
.mapToInt()
// these are common operation that can directly manipulate the procedure.
In the below example, the program just completed the task with very few lines of code.
- to sort
- to limit the size
- to collect to the list
public static void main(String[] args) {
List<String> str = List.of("g", "h","a", "b", "c", "d", "e", "f");
List<String> stream = str.stream()
.sorted()
.limit(4)
.collect(Collectors.toList());
System.out.println(stream);
}
}
// [a, b, c, d]
Some notes on Java Stream API
- To successfully execute a stream, complete blocks are required, beginning with
stream()
and ending with.collect()
, containing the code block within them - stream cannot be reused, hence we cannot redeclare the same stream
- stream only query the collection, not mutate the collection
Stream API can make the code more readable, also considered as part of functional programming paradigms. The advantanges in clude
- to reduce repetitive code (boilerplate), which will cause potential errors
- to increase the efficiency
For example, there are two sections of code: one is a traditional loop, which tells the program how to do something; and the other is a method from the Iterable interface, which tells the program what to do. (as I mentioned in my previous article introducing Streams and Lambda)
public class Main {
public static void main(String[] args) {
List<String> allColors = List.of("Red", "Blue", "Yellow");
// how to do
for(String color : allColors) {
System.out.println(color);
}
// what to do
allColors.forEach(color -> System.out.println(color));
// what to do - use method reference
allColors.forEach(System.out::println);
}
}