Java : Streams and Lambda
The purpose of streams and lambda is to
Tell the computer "what to do" instead of "how to do".
Below is the example of looping over the colors traditionally.
List<String> allColors = List.of("Red", "Blue", "Yellow");
for (String color : allColors) {
System.out.println();
}
Lambda
- an implementation of an interface with single abstract method (functional interface)
List allColors = List.of("Red", "Blue", "Yellow");
allColors.forEach(color -> System.out.printLn(color));
That reminds me of the arrow function in JavaScript
const allColors = ["Red", "Blue", "Yellow"];
allColors.forEach(color => {
console.log(color);
});
Same result
Red
Blue
Yellow
Stream
- the collection of stream will be immutable
- the stream cannot be reused
- pipeline operation
- source to get (
.stream()
) - intermediate operation(
.limit()
) - terminal operation(
.collect()
) - need at least a source and a terminal operation
- source to get (
List<String> str = List.of("a", "b", "c");
// looping
str.stream().forEach(System.out::println);
// filtering
str.stream()
.filter(s -> s.startsWith("a"))
.forEach(System.out::println);
// uppercasing
str.stream()
.map(String::toUpperCase)
.forEach(System.out::println);
// checking
boolean allContainB = str.stream()
.allMatch(s -> s.contains("b"));
System.out.println("All contain 'b': " + allContainB);
Except above, there are many other terminal operations like: .count()
.findFirst()
to speed up and make the operation more concise and intuitive.