Functional programming Flashcards
Java Functional Interface
- Functional interfaces Definition:
a. only 1 abstract method.
b. default method not count static method does not
c. count methods from Object class do not count
@FunctionalInterface
- this helps to check at compile time if this interface is a functional interface
2.Java until function - 43 of them, in 4 categories
1. The consumers
ConsumerT> void accept( t)
BiConsumerT> void accept(T t, vv)
Consumer Person perconsumer = System.out.println; perConsumer.accept();
- The supplier
Supplier I get();
Supplier perSupplier = Person:: new
Person p = perSupplier.get(); - The Functions
Function R apply(T t, v v);
UnaryOperator extends Function BinaryOperator extends BiFunction
4. The predicates (filters) Predicate boolean test( t); BiPredicate boolean test(T t, Vv) --Chaining Predicate and(Predicate super T> other) or(Predicate super T> other) negate()
static Predicate is Equal(Object targetRef) Predicate pl = 3 -> s.length < 20;
Predicate p2 = 5 -> s.length() > 2;
Predicate p3 = pi.and(p2)
Predicate p4 = Predicate.isEqual(“ABC”);
- Function Interface for primitive types
IntPredicate boolean test(int value)
IntFunction R apply(int value)
IntToDoubleFunction double applyAsDouble(int value) - Comparator Vs Comparable
Comparable
int compareTo(T t);
Comparator int compare (T 01, T 02) comparing (Function keyExtractor) thenComparing (Function keyExtractor) default Comparatorreversed static Comparator reverse
Stream API
Interfaces: Stream IntStream Longstream DoubleStream
Why we have Stream?
Avoid building intermediate structures in implementing map/filter/reduce
A stream does not holding any data, it pulls/connects data it processes from a source
A stream does not modify the data it processes
The source is unbounded - Stream do not know the source size at build time
List pp = …
Stream = pp.stream();
the is still in the List, not transformed into the stream.
How to build a stream?
Steam.empty Stream.of(“a”);
Stream.of(“a”, “b”,”C”)
Stream.generate(O -> “one”).forEach(System.out::printin);
infinite generate “one”
IntStream.range(0, endIndexnotInclusive) IntStream.of(1,2,3)
Stream lines = Files.lines(path)
Method on Stream?
1.map method:
peek (System.out::printin) - used mainly for debugging purpose
flatMap()
2.primitiveTypes:
mapToInt
mapToLong
3.filtering method:
filter(predicate)
optionalDouble findAny() - return anyone
optionalDouble findFirst() - return firstOne
boolean AllMatch(predicate)
boolean AnyMatch(predicate)
4.Reducing method: limit(3) skip(2) min() max() sum() sorted() count() average() reduce(identityElement, BinaryOperator)
What is a pure function?
- always returns the same value for same arguments
2. does not have any side effects ( modifying a global variable)
Map/Filter/Reduce Pattern
Using stream() is very efficient, because does not produce any intermediate lists/objects, thus reduce memory footprint
Example: Compute the average age of person that older than 20
1. Map ‘Person’ to ‘Age’
2. Filter Age > 20
3. Reduce compute average
When using Reduce
1. When using parallel reduce, the operation must be associative
apply(apply(a,b),c) = apply(a, apply(b,c))
parallelism performed by JVM is build on fork/join framework
operations that is not associative:
(a+b)/2
aa + bb ect…
associative: a+b, a*b
2.Be careful when there is no identity elements(default value when no elements)
Using Optional to handle when there is no value, return an ‘Optional’ of empty, when getting a value, throw a NoSuchElementException