Speaker: Oleg Tsal-‐Tsalko(@tsaltsol)
Lambdas HOL
About me Oleg Tsal-‐Tsalko Lead So:ware Engineer at EPAM Systems. Speaker, acEve member of Kiev JUG. ParEcipate in different educaEonal iniEaEves and JCP/AdoptJSR programs.
Stream API
-‐ An abstracEon that supports bulk operaEons over sequence of elements
-‐ Not a data structure -‐ Simple and logical chaining of operaEons -‐ Lazy evaluaEon -‐ Internal parallelism if required -‐ Concept of funcEonal programming in Java
txns.stream() .filter(t -‐>t.getBuyer().getAge()>=65) .map(Txn::getSeller) .disEnct() .sort(comparing(Seller::getName)) .forEach(s -‐> System.out.println(s.getName());
Fluent and Simple
How can I get a Stream to work with?
• CollecEon.stream() • IntStream.range() • Stream.of() • Arrays.stream() • BufferedReader.lines() • CharSequence.chars() • Pa`ern.splitAsStream()
Internal iteraEon over external
Is there signifficant difference? for (Item item : items){
process(item); } items.forEach(item -‐> process(item));
Lambda expressions A lambda expression is an anonymous funcEon – Has an argument list, a return type, and a body (Object o) -‐> o.toString() – A method reference is a reference to an exisEng method Object::toString – Lambdas can refer to (capture) values from the enclosing lexical scope (Person p) -‐>p.getName().equals(name) – Compiler can o:en infer argument types from context p -‐> p.getName().equals(name) – Can be used whenever/wherever you use anonymous classes with single method You can now pass behavior as a data between your objects
Using lambdas
FileFilter x = (File f) -> f.canRead();
FileFilter x = File::canRead;
FileFilter x = new FileFilter() { public boolean accept(File f) { return f.canRead(); } };
What’s your type? Since Java doesn’t have FuncEon type on it’s own Lambda’s type evaluated to some FuncEonal interface: Runnable r = () -‐> { doSmth(); }; Callable c = () -‐> calcResult(); Comparator comp = (o1, o2) -‐> compare(o1, o2);
FuncEonal interfaces java.u&l.func&on Package: Predicate<T>
Determine if the input of type T matches some criteria Consumer<T>
Accept a single input argumentof type T, and return no result Function<T, R>
Apply a funcEon to the input type T, generaEng a result of type R java.u&l.stream Package: Collector<T, A, R>
Used to collect stream of elements of type T into single result of type R
Collectors Contains number of predefined Collectors
Influence on exisEng classes? java.lang.Iterable#forEach() java.uEl.CollecEon#stream() java.uEl.CollecEon#parallelStream() java.uEl.Comparator#comparing(…) java.uEl.Comparator#thenComparing(…) java.uEl.Comparator#reverse() …
InstrucEons
• Download test project from GitHub: h`ps://github.com/olegts/LambdasHacking • Import it in your favorite IDE (IDEA*) with JDK8.
• Open single Exercises class. • Fix as much tests as you can going one by one removing @Ignore annotaEon and coding up TODOs.
Thank you!
Oleg Tsal-‐Tsalko Email: [email protected] Twi`er: @tsaltsol