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

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

on

  • 4,172 views

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

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

Statistics

Views

Total Views
4,172
Views on SlideShare
2,064
Embed Views
2,108

Actions

Likes
0
Downloads
4
Comments
0

10 Embeds 2,108

http://odjug.blogspot.com 2016
http://odjug.blogspot.ru 55
http://odjug.blogspot.nl 19
http://odjug.blogspot.de 5
http://translate.googleusercontent.com 4
http://odjug.blogspot.in 3
http://odjug.blogspot.cz 2
http://odjug.blogspot.co.il 2
http://odjug.blogspot.co.at 1
http://odjug.blogspot.com.au 1
More...

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • Hello and welcome to Sigma Ukraine!
  • А нужен ли Б?
  • Старый код работает, новый на старых классах тоже

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

  • LAMBDA IN JAVA 8MIKE PONOMARENKO
  • ТЕОРИЯ Что такое замыкание (Lambda Expressions, JSR 335) Изменения в языке Сопутствующие изменения2 Sigma Ukraine
  • JSR 335EARLY DRAFT R3
  • ТЕОРИЯ - ЗАМЫКАНИЯ Lambda expression – Анонимный метод – Может обращаться к переменным в локальной области – Нет лишнего .class при компиляции (x, y) => { System.out.println("The sum of x and y equals " + (x+y) ) () => {return outerValue;}4 Sigma Ukraine
  • ПРИМЕР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
  • ПРИМЕР{Runnable r = ()->{System.out.println("hello");};(new Thread(r)).start();}6 Sigma Ukraine
  • ПРИМЕР{String ref = "a";Runnable r = () -> {System.out.println(ref);};r.run();System.out.println(ref);} 7 Sigma Ukraine
  • ПРИМЕРString ref = "a";Runnable r = new Runnable(){ public void run(){ System.out.println(ref); }};r.run();System.out.println(ref); 8 Sigma Ukraine
  • ПРИМЕР{List<String> strings = new LinkedList<String>();Collections.sort(strings, (String a,String b) -> { return -(a.compareTo(b)); });} 9 Sigma Ukraine
  • ПРИМЕР{List<String> strings = new LinkedList<String>();Collections.sort(strings, (a, b) -> -(a.compareTo(b)));} 10 Sigma Ukraine
  • ТЕРИЯ, ИЗМЕНЕНИЯ В ЯЗЫКЕ Функциональный интерфейс – “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
  • ТЕОРИЯ, МЕТОД ПО УМОЛЧАНИЮinterface A{ void doA();}interface B extends A{ default void doB() { doA(); doA(); }} 12 Sigma Ukraine
  • ТЕОРИЯ, МЕТОД ПО УМОЛЧАНИЮinterface A{ void doA(); default void doB() { doA(); doA(); }} 13 Sigma Ukraine
  • ТЕОРИЯ, ССЫЛКА НА МЕТОД“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
  • ПРИМЕРCollection<String> c = Arrays.asList("A","B","CD");System.out.println(sum(c,String::length));15 Sigma Ukraine
  • ПРИМЕР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
  • ПРИМЕР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
  • JDK System.out.println(c.stream().map(String::length).sum());18 Sigma Ukraine
  • ТЕОРИЯ Добавляется в рантайм Множественное наследование поведения. Похоже на “C# extension methods” Наследование –1. Суперкласс (“class wins”)2. Более спецефичный интерфейс (“subtype wins”)3. Делать вид что метод абстрактный 1. Реализующий класс должен сделать выбор сам. A.super.m()19 Sigma Ukraine
  • JDKinterface Iterator<T> { boolean hasNext(); T next(); default void remove() { throw new UnsupportedOperationException(); }} 20 Sigma Ukraine
  • JDK interface Collection – forEach – removeIf(Predicate) – stream() – parallelStream()21 Sigma Ukraine
  • 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
  • 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
  • JDK System.out.println(c.stream().map(String::length).sum());24 Sigma Ukraine
  • Thank you for your attention!