Your SlideShare is downloading. ×
Lambda выражения и Java 8
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

Lambda выражения и Java 8

3,716
views

Published on

"Lambda выражения и Java 8" by …

"Lambda выражения и Java 8" by
Михаил Пономаренко, Tech Lead, компания Sigma Ukraine

Published in: Technology

0 Comments
3 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
3,716
On Slideshare
0
From Embeds
0
Number of Embeds
11
Actions
Shares
0
Downloads
9
Comments
0
Likes
3
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide
  • Hello and welcome to Sigma Ukraine!
  • А нужен ли Б?
  • Старый код работает, новый на старых классах тоже
  • Transcript

    • 1. LAMBDA IN JAVA 8MIKE PONOMARENKO
    • 2. ТЕОРИЯ Что такое замыкание (Lambda Expressions, JSR 335) Изменения в языке Сопутствующие изменения2 Sigma Ukraine
    • 3. JSR 335EARLY DRAFT R3
    • 4. ТЕОРИЯ - ЗАМЫКАНИЯ Lambda expression – Анонимный метод – Может обращаться к переменным в локальной области – Нет лишнего .class при компиляции (x, y) => { System.out.println("The sum of x and y equals " + (x+y) ) () => {return outerValue;}4 Sigma Ukraine
    • 5. ПРИМЕРerror: local variables referenced from a lambdaexpression must be final or effectively final{String ref = "a";Runnable r = () -> {ref = "b";};r.run();System.out.println(ref);} 5 Sigma Ukraine
    • 6. ПРИМЕР{Runnable r = ()->{System.out.println("hello");};(new Thread(r)).start();}6 Sigma Ukraine
    • 7. ПРИМЕР{String ref = "a";Runnable r = () -> {System.out.println(ref);};r.run();System.out.println(ref);} 7 Sigma Ukraine
    • 8. ПРИМЕРString ref = "a";Runnable r = new Runnable(){ public void run(){ System.out.println(ref); }};r.run();System.out.println(ref); 8 Sigma Ukraine
    • 9. ПРИМЕР{List<String> strings = new LinkedList<String>();Collections.sort(strings, (String a,String b) -> { return -(a.compareTo(b)); });} 9 Sigma Ukraine
    • 10. ПРИМЕР{List<String> strings = new LinkedList<String>();Collections.sort(strings, (a, b) -> -(a.compareTo(b)));} 10 Sigma Ukraine
    • 11. ТЕРИЯ, ИЗМЕНЕНИЯ В ЯЗЫКЕ Функциональный интерфейс – “A functional interface is an interface that has just one abstract method, and thus represents a single function contract. (In some cases, this "single" method may take the form of multiple abstract methods with override-equivalent signatures inherited from superinterfaces; in this case, the inherited methods logically represent a single method.)” - JSR Метод по умолчанию Ссылка на метод11 Sigma Ukraine
    • 12. ТЕОРИЯ, МЕТОД ПО УМОЛЧАНИЮinterface A{ void doA();}interface B extends A{ default void doB() { doA(); doA(); }} 12 Sigma Ukraine
    • 13. ТЕОРИЯ, МЕТОД ПО УМОЛЧАНИЮinterface A{ void doA(); default void doB() { doA(); doA(); }} 13 Sigma Ukraine
    • 14. ТЕОРИЯ, ССЫЛКА НА МЕТОД“A method reference is used to refer to a method without invoking it;a constructor reference is similarly used to refer to a constructor without creating a new instance of the named class or array type.” - JSR System::getProperty "abc"::length String::length super::toString ArrayList::new int[]::new14 Sigma Ukraine
    • 15. ПРИМЕРCollection<String> c = Arrays.asList("A","B","CD");System.out.println(sum(c,String::length));15 Sigma Ukraine
    • 16. ПРИМЕРinterface Code<T,R>{ R exec(T input);}public static <T,R extends Number> long sum(Collection<T> c ,Code<T,R> cd){ long rz = 0; for(T t : c){ R v = cd.exec(t); if(v!=null) { rz+=v.longValue(); } } return rz;} 16 Sigma Ukraine
    • 17. ПРИМЕРimport java.util.function.*;public static <T,R extends Number> long sum(Collection<T> c , Function<T,R> cd){ long rz = 0; for(T t : c){ R v = cd.apply(t); if(v!=null) { rz+=v.longValue(); } } return rz;} 17 Sigma Ukraine
    • 18. JDK System.out.println(c.stream().map(String::length).sum());18 Sigma Ukraine
    • 19. ТЕОРИЯ Добавляется в рантайм Множественное наследование поведения. Похоже на “C# extension methods” Наследование –1. Суперкласс (“class wins”)2. Более спецефичный интерфейс (“subtype wins”)3. Делать вид что метод абстрактный 1. Реализующий класс должен сделать выбор сам. A.super.m()19 Sigma Ukraine
    • 20. JDKinterface Iterator<T> { boolean hasNext(); T next(); default void remove() { throw new UnsupportedOperationException(); }} 20 Sigma Ukraine
    • 21. JDK interface Collection – forEach – removeIf(Predicate) – stream() – parallelStream()21 Sigma Ukraine
    • 22. JDKdefault Stream<E> stream() { return Streams.stream(() -> Streams.spliterator(iterator(), size(), Spliterator.SIZED), Spliterator.SIZED);}default Stream<E> parallelStream() { return stream().parallel();} 22 Sigma Ukraine
    • 23. JDKpublic interface Stream<T> extends BaseStream<T, Stream<T>> { Stream<T> filter(Predicate<? super T> predicate); <R> Stream<R> map(Function<? super T, ? extends R> mapper); Stream<T> sorted(); Optional<T> reduce(BinaryOperator<T> reducer); default Optional<T> max(Comparator<? super T> comparator) { return reduce(Comparators.greaterOf(comparator)); } boolean anyMatch(Predicate<? super T> predicate);} 23 Sigma Ukraine
    • 24. JDK System.out.println(c.stream().map(String::length).sum());24 Sigma Ukraine
    • 25. Thank you for your attention!