Stream or LoopJava 8 Stream API
Nikolay Petkov
Java 8 Goodies
● Lambda expressions aka functional interfaces
● Method references● Default methods
Functional Interface
Lambda Expressions
Lambda Expressions
Method Reference
● Static method● Instance method of particular instance● Instance method of particular type● Constructor
Static method reference
Instance method reference
Default Method
public interface Developer {void writeCode();
default void writeTest() {throw new ImPerfectException(
“Why bother? My code is perfect”);}
}
External vs Internal Iteration
for (Car car : cars) {if (“BMW”.equals(car.getBrand()) {
car.setOwner(“Alex”) ;}
}
cars.forEach((car) -> {if (“BMW”.equals(car.getBrand()) {
car.setOwner(“Alex”) ;}
});
Stream API
Classes to support functional-style operations on streams of elements, such as map-reduce transformations on collections.
int oldestBmwAge = cars.stream().filter((car) -> “BMW”.equals(car.getBrand())).mapToInt((car) -> car.getAge()).max();
Streams vs Collections
● Not a storage● Functional by design● Possibly unbounded● Lazy by nature● Use and discard
Stream pipeline
A stream pipeline consists of:● a source (such as a Collection, an array, a
generator function, or an I/O channel);● followed by zero or more intermediate
operations such as Stream.filter or Stream.map;
● and a terminal operation such as Stream.forEach or Stream.reduce.
Execution begins when the terminal operation is invoked, and ends when the terminal operation completes
Source
● Collection.stream()● Arrays.stream(Object[])● Stream.of(Object[])● IntStream.range(int, int)● BufferedReader.lines();● Files.list(Path dir)● etc.
Intermediate - filter
Returns a stream consisting of the elements of this stream that match the given predicate.
Stream<T> filter(Predicate<? super T> predicate)
filter((String s) -> s.lenght() < 20)filter((String s) -> String::isEmpty))
Intermediate - sorted
Returns a stream consisting of the elements of this stream, sorted according to the provided Comparator.
sorted(Comparator<? super T> comparator)
sorted(comparing(Person::getLastName)sorted((s1, s2) -> s1.lenght() > s2.lenght())
Intermediate - map
Returns a stream consisting of the results of applying the given function to the elements of this stream. The map operation is kind of transformation of the stream elements to another elements.
map(Function<T,R> mapper)
mapToInt((String s) -> s.lenght())map((User u) -> User::getRole())
Terminal – max/min/sum/count
Returns the maximum/minimum element of this stream according to the provided Comparator
max(Comparator<? super T> comparator)
max(comapring(Persone::getAge))stream.mapToInt(Persone::getAge).sum()
A lot more follows
Questions?