Tuesday, May 3, 2016

JAVA 8 - what is Functional Interface and Lambda Expression, etc

Functional Interface is an interface with only one method.
- default methods do not count
- static methods do not count
- methods from the Object class do not count

A Lambda Expression is an instance of a functional interface.
public interface Predicate<T> {
    boolean test(T t);
}

Implementation would be:
Predicate<String> predicate = s -> s.length() < 20;
System.out.println(predicate.test("Hello world!"));//expicite way of using it


Four categories of java.util.function: 
- The Consumers 
public interface Consumer<T> {
    public void accept(T t);
}
Consumer<String> printer = s -> System.out.println(s);
Consumer<String> printerAlt = System.out::println;

- The Supplier 
public interface Supplier<T> {
    public T get();
}
Supplier<Person> personSupplier = () -> new Person();
Supplier<Person> personSupplierAlt = Person::new;

- The Functions 
public interface Function<T, R> {
    public R apply(T t);
}
Function<Person, Integer> ageMapper = person -> person.getAge();
Function<Person, Integer> ageMapperAlt = Person::getAge;

- The Predicates

public interface Predicate<T> {
    boolean test(T t);
}
Predicate<String> predicate = s -> s.length() < 20;
System.out.println(predicate.test("Hello world!"));


Map, Filter, Reduce over collection

MAP changes the TYPE of the collection, not the size.

FILTER changes the SIZE of the collection and preserves its type.






REDUCE completely changes the TYPE of the collection.







Java 7 implementation:





Parallel Reduce computation on computer with 2 Cores Processor
java 8 parallel reduce computed on 2 core processor







Streams
java 8 streams defenition








Intermediate and Terminal calls of Stream;
Intermediate call return Stream (e.g. Stream.peek)
Terminal call returns something else or is void and thus trigger the processing (Stream.forEach)

Stream skip() and limit()
java 8 stream skip and limit methods
















Stream Match Reduction - short-circuiting terminal operation 
Stream.anyMatch, allMatch, NoneMatch (all return boolean)
Short-circuiting operations of Stream may not to evaluate the predicate for all the elements in the stream.

Stream Find Reduction - short-circuiting terminal operation
Stream.findFirst, findAny (all may return Optional that can be empty is there no such item)
Optional<Person> opt = people.stream().findAny(p -> p.getAge() > 20);

















No comments: