SlideShare a Scribd company logo
1 of 15
Java 8 jest tuż za rogiem
czyli programowanie funkcyjne
na żywo i w przykładach
Co jest złego w klasach anonimowych?
List<Person> list = ...
Collections.sort(list, new Comparator<Person>() {
@Override
public int compare(Person p1, Person p2) {
return p1.getName().compareTo(p2.getName());
}
});
Spróbujmy tak...
Collections.sort(list, (Person p1, Person p2) ->
p1.getName().compareTo(p2.getName())
);
... albo tak
Collections.sort(list, (p1, p2) ->
p1.getName().compareTo(p2.getName())
);
Składnia
(int i) -> { System.out.println(i+1); }
(String s, int offset) -> {
return s.charAt(offset); }
<T> (T i) -> { }
i -> { System.out.println(i+1); }
(s, offset) -> s.charAt(offset);
() -> {}
To się nie skompiluje
(final x) -> {}
(int x, y) -> 3.14
() -> { 3.14; }
i, j -> i*j // bo nie wiadomo co to: foo(i, j -> i *j)
-> "foo"
list.sort(_.getSize()); // No placeholder syntax (wunderbars)
Kontekst
• Przypisania
IntConsumer c = i -> { System.out.println(i); };
• Wywołania:
SwingUtilities.invokeLater(() -> button.setEnabled(false));
• Rzutowania:
Object o = (Callable<Integer>) () -> 42;
• Zwracania:
public static <T> Function<T, T> identity() {
return t -> t;
}
Kod jako obiekty
interface Runnable { void run(); }
interface Callable<T> { T call(); }
interface ActionListener {
void actionPerformed(ActionEvent a);
}
interface Comparator<T> {
int compare(T o1, T o2);
boolean equals(Object obj);
}
Odwołania do zmiennych z poza
zakresu...
int getAdultCount(List<Person> people, int threshold) {
return Collections.filter(people, p -> p.getAge() > threshold).size();
}
void registerNotifier(JButton button, JLabel label) {
button.addActionListener(e -> label.setText("Ok"));
}
Zmiennie lokalne, które nie są zmieniane otrzmują modyfikator final.
... mogą myć niebezpieczne
int accumulatedExperience = 0;
people.forEach(p -> {
accumulatedExperience += p.getEmploymentYears();
});
błąd kompilacji
... mogą myć niebezpieczne
/* final */ int[] accumulatedExperience = { 0 };
people.forEach(p -> {
accumulatedExperience[0] += p.getEmploymentYears();
});
Nie próbujcie tego w domu
(ani na produkcji)
... mogą myć niebezpieczne
/* final */ AtomicInteger accumulatedExperience = new AtomicInteger();
people.forEach(p -> {
accumulatedExperience.addAndGet(p.getEmploymentYears());
});
Działa! Ale lepiej tak:
people.stream().map(Person::getEmploymentYears).reduce(0, Integer::sum)
Referencje do metod
class Math {
public static int max(int a, int b) { ... }
}
interface Operator<T> {
T eval(T left, T right);
}
Operator<Integer> lambda = (a, b) -> Math.max(a, b);
Operator<Integer> methodRef = Math::max;
...statycznych
class Reducer {
public <T> static reduce(T base, BinaryOperator<T> op, T... items) {
for(T item : items) {
base = op.apply(base, item);
}
}
}
// result is 9
Reducer.reduce(0, Math::max, 1, 6, 9, 8);
// result is 24
Reducer.reduce(0, Integer::sum, 1, 6, 9, 8);
...istancji i konstruktorów
interface Function {
U apply(T t);
}
Function<String, Integer> getLength = s -> s.length;
Function<String, Integer> getLength = String::length;
getLength.apply("4Developers") == 11
Function<Integer, int[]> factory = int[]::new;
Supplier<ArrayList<Person>> supplier = ArrayList<Person>::new;
Strumienie
• Ewolucja kolekcji
• Dostarczają operacje do grupowego (bulk) przetwarzania elementów kolekcji
• Jednorazowego użytku – elementy są niedostępne po ich odczytaniu
• Łatwe przejście w tryb przetwarzania wielowątkowego
• Wspierają funkcjonalny styl programowania
• Idee zadoptowane w pozostałych częściach JDK

More Related Content

Viewers also liked

Yazilim kurslari-istanbul
Yazilim kurslari-istanbulYazilim kurslari-istanbul
Yazilim kurslari-istanbulzeynep_zyn97
 
The Wonders of Alabama
The Wonders of AlabamaThe Wonders of Alabama
The Wonders of AlabamaP9P
 
Activities involved in succesion process among asian and african owned business
Activities involved in succesion process among asian and african owned businessActivities involved in succesion process among asian and african owned business
Activities involved in succesion process among asian and african owned businessJohn Johari
 
Arcadis presentatie nl 2012
Arcadis presentatie nl 2012Arcadis presentatie nl 2012
Arcadis presentatie nl 2012anwaterloos
 
We make our bookmarks
We make our bookmarksWe make our bookmarks
We make our bookmarksmsourgiad
 
Cool To Call - Guida all'installazione
Cool To Call - Guida all'installazioneCool To Call - Guida all'installazione
Cool To Call - Guida all'installazioneCOOL
 
Huraangui
HuraanguiHuraangui
HuraanguiCopy Mn
 
Lists4Europe 2016 presentazione
Lists4Europe 2016 presentazioneLists4Europe 2016 presentazione
Lists4Europe 2016 presentazionemls marco merlo
 
The Catholic Church as a Prophet of Justice
The Catholic Church as a Prophet of JusticeThe Catholic Church as a Prophet of Justice
The Catholic Church as a Prophet of JusticeP9P
 
A arte da direção das almas
A arte da direção das almasA arte da direção das almas
A arte da direção das almasAlberto Oliveira
 
The Local-Vocal-Mobile Connection: Why Mobile is the new Local - Purna Virji-...
The Local-Vocal-Mobile Connection: Why Mobile is the new Local - Purna Virji-...The Local-Vocal-Mobile Connection: Why Mobile is the new Local - Purna Virji-...
The Local-Vocal-Mobile Connection: Why Mobile is the new Local - Purna Virji-...Purna Virji
 
музей в роли брендингового агентства
музей в роли брендингового агентствамузей в роли брендингового агентства
музей в роли брендингового агентстваAnna Stepnova
 

Viewers also liked (17)

Yazilim kurslari-istanbul
Yazilim kurslari-istanbulYazilim kurslari-istanbul
Yazilim kurslari-istanbul
 
The Wonders of Alabama
The Wonders of AlabamaThe Wonders of Alabama
The Wonders of Alabama
 
Activities involved in succesion process among asian and african owned business
Activities involved in succesion process among asian and african owned businessActivities involved in succesion process among asian and african owned business
Activities involved in succesion process among asian and african owned business
 
Arcadis presentatie nl 2012
Arcadis presentatie nl 2012Arcadis presentatie nl 2012
Arcadis presentatie nl 2012
 
gabby a
gabby agabby a
gabby a
 
We make our bookmarks
We make our bookmarksWe make our bookmarks
We make our bookmarks
 
Cool To Call - Guida all'installazione
Cool To Call - Guida all'installazioneCool To Call - Guida all'installazione
Cool To Call - Guida all'installazione
 
Huraangui
HuraanguiHuraangui
Huraangui
 
Lists4Europe 2016 presentazione
Lists4Europe 2016 presentazioneLists4Europe 2016 presentazione
Lists4Europe 2016 presentazione
 
The Catholic Church as a Prophet of Justice
The Catholic Church as a Prophet of JusticeThe Catholic Church as a Prophet of Justice
The Catholic Church as a Prophet of Justice
 
Marcelo
MarceloMarcelo
Marcelo
 
Billar
BillarBillar
Billar
 
A arte da direção das almas
A arte da direção das almasA arte da direção das almas
A arte da direção das almas
 
The Local-Vocal-Mobile Connection: Why Mobile is the new Local - Purna Virji-...
The Local-Vocal-Mobile Connection: Why Mobile is the new Local - Purna Virji-...The Local-Vocal-Mobile Connection: Why Mobile is the new Local - Purna Virji-...
The Local-Vocal-Mobile Connection: Why Mobile is the new Local - Purna Virji-...
 
музей в роли брендингового агентства
музей в роли брендингового агентствамузей в роли брендингового агентства
музей в роли брендингового агентства
 
Infarto a solas
Infarto a solasInfarto a solas
Infarto a solas
 
Evaluation 4
Evaluation 4Evaluation 4
Evaluation 4
 

More from Tomasz Kowalczewski

More from Tomasz Kowalczewski (14)

How I learned to stop worrying and love the dark silicon apocalypse.pdf
How I learned to stop worrying and love the dark silicon apocalypse.pdfHow I learned to stop worrying and love the dark silicon apocalypse.pdf
How I learned to stop worrying and love the dark silicon apocalypse.pdf
 
Is writing performant code too expensive?
Is writing performant code too expensive? Is writing performant code too expensive?
Is writing performant code too expensive?
 
Is writing performant code too expensive?
Is writing performant code too expensive? Is writing performant code too expensive?
Is writing performant code too expensive?
 
Is writing performant code too expensive?
Is writing performant code too expensive?Is writing performant code too expensive?
Is writing performant code too expensive?
 
Deep dive reactive java (DevoxxPl)
Deep dive reactive java (DevoxxPl)Deep dive reactive java (DevoxxPl)
Deep dive reactive java (DevoxxPl)
 
Everybody Lies
Everybody LiesEverybody Lies
Everybody Lies
 
Forgive me for i have allocated
Forgive me for i have allocatedForgive me for i have allocated
Forgive me for i have allocated
 
AWS Java SDK @ scale
AWS Java SDK @ scaleAWS Java SDK @ scale
AWS Java SDK @ scale
 
Measure to fail
Measure to failMeasure to fail
Measure to fail
 
Reactive Java at JDD 2014
Reactive Java at JDD 2014Reactive Java at JDD 2014
Reactive Java at JDD 2014
 
Reactive Java (33rd Degree)
Reactive Java (33rd Degree)Reactive Java (33rd Degree)
Reactive Java (33rd Degree)
 
Reactive Java (GeeCON 2014)
Reactive Java (GeeCON 2014)Reactive Java (GeeCON 2014)
Reactive Java (GeeCON 2014)
 
Introduction to Reactive Java
Introduction to Reactive JavaIntroduction to Reactive Java
Introduction to Reactive Java
 
Java gets a closure
Java gets a closureJava gets a closure
Java gets a closure
 

Java 8 jest tuż za rogiem

  • 1. Java 8 jest tuż za rogiem czyli programowanie funkcyjne na żywo i w przykładach
  • 2. Co jest złego w klasach anonimowych? List<Person> list = ... Collections.sort(list, new Comparator<Person>() { @Override public int compare(Person p1, Person p2) { return p1.getName().compareTo(p2.getName()); } });
  • 3. Spróbujmy tak... Collections.sort(list, (Person p1, Person p2) -> p1.getName().compareTo(p2.getName()) ); ... albo tak Collections.sort(list, (p1, p2) -> p1.getName().compareTo(p2.getName()) );
  • 4. Składnia (int i) -> { System.out.println(i+1); } (String s, int offset) -> { return s.charAt(offset); } <T> (T i) -> { } i -> { System.out.println(i+1); } (s, offset) -> s.charAt(offset); () -> {}
  • 5. To się nie skompiluje (final x) -> {} (int x, y) -> 3.14 () -> { 3.14; } i, j -> i*j // bo nie wiadomo co to: foo(i, j -> i *j) -> "foo" list.sort(_.getSize()); // No placeholder syntax (wunderbars)
  • 6. Kontekst • Przypisania IntConsumer c = i -> { System.out.println(i); }; • Wywołania: SwingUtilities.invokeLater(() -> button.setEnabled(false)); • Rzutowania: Object o = (Callable<Integer>) () -> 42; • Zwracania: public static <T> Function<T, T> identity() { return t -> t; }
  • 7. Kod jako obiekty interface Runnable { void run(); } interface Callable<T> { T call(); } interface ActionListener { void actionPerformed(ActionEvent a); } interface Comparator<T> { int compare(T o1, T o2); boolean equals(Object obj); }
  • 8. Odwołania do zmiennych z poza zakresu... int getAdultCount(List<Person> people, int threshold) { return Collections.filter(people, p -> p.getAge() > threshold).size(); } void registerNotifier(JButton button, JLabel label) { button.addActionListener(e -> label.setText("Ok")); } Zmiennie lokalne, które nie są zmieniane otrzmują modyfikator final.
  • 9. ... mogą myć niebezpieczne int accumulatedExperience = 0; people.forEach(p -> { accumulatedExperience += p.getEmploymentYears(); }); błąd kompilacji
  • 10. ... mogą myć niebezpieczne /* final */ int[] accumulatedExperience = { 0 }; people.forEach(p -> { accumulatedExperience[0] += p.getEmploymentYears(); }); Nie próbujcie tego w domu (ani na produkcji)
  • 11. ... mogą myć niebezpieczne /* final */ AtomicInteger accumulatedExperience = new AtomicInteger(); people.forEach(p -> { accumulatedExperience.addAndGet(p.getEmploymentYears()); }); Działa! Ale lepiej tak: people.stream().map(Person::getEmploymentYears).reduce(0, Integer::sum)
  • 12. Referencje do metod class Math { public static int max(int a, int b) { ... } } interface Operator<T> { T eval(T left, T right); } Operator<Integer> lambda = (a, b) -> Math.max(a, b); Operator<Integer> methodRef = Math::max;
  • 13. ...statycznych class Reducer { public <T> static reduce(T base, BinaryOperator<T> op, T... items) { for(T item : items) { base = op.apply(base, item); } } } // result is 9 Reducer.reduce(0, Math::max, 1, 6, 9, 8); // result is 24 Reducer.reduce(0, Integer::sum, 1, 6, 9, 8);
  • 14. ...istancji i konstruktorów interface Function { U apply(T t); } Function<String, Integer> getLength = s -> s.length; Function<String, Integer> getLength = String::length; getLength.apply("4Developers") == 11 Function<Integer, int[]> factory = int[]::new; Supplier<ArrayList<Person>> supplier = ArrayList<Person>::new;
  • 15. Strumienie • Ewolucja kolekcji • Dostarczają operacje do grupowego (bulk) przetwarzania elementów kolekcji • Jednorazowego użytku – elementy są niedostępne po ich odczytaniu • Łatwe przejście w tryb przetwarzania wielowątkowego • Wspierają funkcjonalny styl programowania • Idee zadoptowane w pozostałych częściach JDK