gdg almaty. Функциональное программирование в java 8
DESCRIPTION
О функциональном программировании (ФП), преимуществах его использования и о том, какие возможности для него добавили в новом релизе Java. Слушатели также узнают, почему уже сейчас стоит начать изучать ФП. Митап состоялся ->> https://plus.google.com/u/0/b/100893943920756626864/events/c0b2b1ih9ft0opcdnmdgp3453rkTRANSCRIPT
Sayat SatybaldiyevSoftware Dev. @ Green Apple
Twitter: Sayat_Stb
Google Developers Group Almaty
Google Developers GroupAlmaty
• Некоммерческое сообщество, в основе которого лежит обмен опытом и знаниями технологии Google для разработчиков - Android, Google Maps, App Engine, Chrome, Web Toolkit, Google Plus и другие.
• Среди нас есть программисты, архитекторы, дизайнеры, IT-менеджеры, студенты и руководители. И мы всегда рады новым знакомствам :)
Спонсор фуршета
•
История
Lisp, Schema, Haskell
Как можно выбрать все зеленые яблоки из коллекции красных, желтых и зеленых яблок?
Functional vs Imperative
List<Apple> result = new ArrayList<>();
for(Apple apple: input){
if(apple.getColor.equals("green")){
result.add(apple);
}
}
return result;
Functional vs Imperative
filterApples(input,
(Apple a) -> { a.getColor().equals("green")}
)
Принципы ФП
• Higher Order Functionspass, create, return
• Side Effects Freef(x, y) = x^2 + y ^2
• Immutabilityeasy to reason, multithreaded
Common FP operations
map
Common FP operations
filter
Common FP operations
reduce
Java 8 Lambda Project
The first ever big release since 1.5!
aka Functional Style
First Lambdas
button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { System.out.println("button clicked")}
});
First Lambdas
button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { System.out.println("button clicked")}
});
button.addActionListener(event -> System.out.println("button clicked"));
Синтаксис Lambda Выражений
• Lambda - anonymous function(arg1, arg2...) -> { body }
(int x, int y) -> x + y(x, y) -> x + y() -> System.out.println(“Hello World”)
Functional Interface
T => Boolean@FunctionalInterfacepublic interface Predicate<T>{
boolean test(T t)
}T => void@FunctionalInterfacepublic interface Consumer<T>{
void accept(T t)}T => R@FunctionalInterfacepublic interface Function<T, R>{
R apply(T t)}
Def: A functional interface is an interface with a single abstract method that is used as the type of a lambda expression.
Functional Interface
Represents a function that accepts one argument and produces a result.T => R@FunctionalInterfacepublic interface Function<T, R>{
R apply(T t)}
Function<Apple, String> = (Apple a ) -> a.toString()
Functional Interface
Represents a predicate (boolean-valued function) of one argument. - Filter
T => Boolean@FunctionalInterface
public interface Predicate<T>{boolean test(T t)
}
Predicate<Integer> atLeast5 = ( x ) -> x > 5;
Functional Interface
Represents an operation that accepts a single input argument and returns no result.
T => void@FunctionalInterfacepublic interface Consumer<T>{
void accept(T t)}
Consumer<Apple> = (Apple a) -> System.out.println(a.toString())
Stream APIs
Streams
• No Storage• Lazy Evaluations• Infinite/Finite Stream• Single Usage• Ordered/Unordered• Parallel/Sequential
Streams
Declarative Style
what to do NOT howList<String> myList = Arrays.asList("a1", "a2", "b1", "c2", "c1");
myList
.stream()
.filter(s -> s.startsWith("c"))
.map(String::toUpperCase)
.sorted()
.forEach(System.out::println);
Streams
Pipes-and-filter Style API
Creating Stream API
Arrays.stream()
Stream<Integer> = Stream.of(1, 2, 3)
Infinite
Stream.iterate(0, n-> n + 10)
ex: with limit - fixed size
Stream Operatons
filter(Predicate<T>)
map(Function<R, T>)
sorted(Comparator<T>)
limit(long maxSize)
distinct()
Terminal Stream Operation
Terminal
sum()
max()/min()
average()
forEach()
collect()
Parallel Stream
Количество зеленых яблок в колекции?
int count = 0;for (Apple apple : allApples) {
if (apple.equals("green")) { count++;
} } return count;
Количество зеленых яблок в колекции?
int count = 0;Iterator<Apple> iterator = allApples.iterator(); while(iterator.hasNext()) {
Apple apple = iterator.next(); if (apple.equals("green")) {
count++; }
}
Parallel Streams
public int parallelArraySum() { return albums.parallelStream()
.mapToInt((Track tr) -> tr.getLength) .sum();
} ● Fork and Join Framework● NOT keep order of stream
Performance
private int addIntegers(List<Integer> values) { return values.parallelStream()
.mapToInt(i -> i) .sum();
}
Performance
Performance
Data size
Source data structure
# cores
FP in Java 8
1. FP(ish) programming
2. Declarative
3. Working with Data Processing
Спасибо за внимание
Google Developers Group Almaty
www.GDGalmaty.org
Optional