Presentation is loading. Please wait.

Presentation is loading. Please wait.

JAVA 8 AND FUNCTIONAL PROGRAMMING. What is Functional Programming?  Focus on Mathematical function computations  Generally don’t think about “state”

Similar presentations


Presentation on theme: "JAVA 8 AND FUNCTIONAL PROGRAMMING. What is Functional Programming?  Focus on Mathematical function computations  Generally don’t think about “state”"— Presentation transcript:

1 JAVA 8 AND FUNCTIONAL PROGRAMMING

2 What is Functional Programming?  Focus on Mathematical function computations  Generally don’t think about “state” or data that changes (since it doesn’t in the math world.)  Prefers recursion over loops  Functions are as “important” as data – can be passed to other functions  Good for parallel computations

3 Lambdas  Lambda expressions: funny-sounding name for functions that are in-line and may not have a formal name  Greek letter used to define a function

4 How to write a Java Lambda  ( parameters ) -> { body }  There are lots of options  You don’t have to have () if only one input  You don’t have to have {} if only one line of output  You don’t have to give the types if it’s obvious in context  All of these are valid:  (int x, int y) -> { return x+y; }  x -> x * x  () -> x

5 More ways to refer to a method Method Reference Type SyntaxExample staticClassName::StaticMethodNameString::valueOf constructorClassName::newArrayList::new specific object instance objectReference::MethodNamex::toString arbitrary object of a given type ClassName::InstanceMethodNameObject::toString

6 But what’s its type?  Everything in Java is really an Object with a type, right?  Java 8 made “functional interfaces”: Interfaces with one and only one non-implemented method  A bunch were added to the library: java.util.function  (Most notable is the Consumer)  You can make your own, too

7 Start with a Collection  Collections now have a forEach method that takes a method reference as parameter.  The code will call the method on each member of the collection, like a loop List intSeq = Arrays.asList(1,2,3); intSeq.forEach(x -> System.out.println(x)); or intSeq.forEach(System.out::println);

8 Sorting Employee class has fields name and payRate Old way: myCollection.sort(new Comparator (){ public int compare(Employee e1, Employee e2){ return e1.getName. compareTo(e2.getName()); } });

9 Sorting Employee class has fields name and payRate New way: myCollection.sort( Comparator.comparing(Employee::getName));

10 Streams  Transient data collections and their associated transformation chain.  Aren’t permanently stored or named  Aren’t like I/O Streams – that’s a different Java use of the word  Think of streaming video – lots of data floats past you. You get to see it but not keep it.

11 Collection to Stream  After you have a collection, List intSeq = Arrays.asList(1,2,3); intSeq.stream()

12 Array to Stream int[] ints = {1,2,3}; Arrays.stream(ints)

13 Stream methods  Some methods leave the stream open:  map (transform one element into another)  filter (keep certain elements only)  sorted  distinct, peek, limit, parallel  Other methods are terminal operations  forEach  toArray  reduce (collapse with a function)  collect  min, max, count, anyMatch, allMatch, nonMatch, findFirst, findAny, iterator, get

14 Examples Collection coll = Arrays.asList(1,2,3,4,5); Integer answer = coll.stream().filter(x -> x%2 ==0) // keep even #s.map(x -> x*x) // square them all.reduce(0, (x,y) -> x+y); // then add em up

15 Examples Collection coll = Arrays.asList(1,2,3,4,5); Integer answer = coll.stream().filter… Integer answer = IntStream.range(1,5).filter…

16 Examples List coll2 = Arrays.asList( "a", "b", "hey", "yes"); List longWords = coll2.stream().filter(x->x.length()>1).collect(Collectors.toList()); longWords.stream().forEach (System.out::println);

17 Examples List coll2 = Arrays.asList( "a", "b", "hey", "yes"); System.out.println( coll2.stream().collect(Collectors.joining("XX")) ); // prints aXXbXXheyXXyes

18 Examples List coll2 = Arrays.asList( "a", "b", "hey", "yes"); long longWordsCount = coll2.stream().filter(x->x.length()>1).count();

19 Examples List coll2 = Arrays.asList( "a", "b", "hey", "yes"); int longWordsSum = coll2.stream().mapToInt(x->x.length()) // use mapToInt so I can sum.sum(); System.out.println(longWordsSum);

20 Optionals  Sometimes we are looking for a value that may or may not exist  Some of the Stream methods return Optional  To test if it value was found, use isPresent()  To get value use get()

21 Example Collection coll = Arrays.asList(1,2,3,4,5); Optional firstBig = coll.stream().filter(x -> x > 2).findFirst(); if(firstBig.isPresent()) System.out.println(firstBig.get());


Download ppt "JAVA 8 AND FUNCTIONAL PROGRAMMING. What is Functional Programming?  Focus on Mathematical function computations  Generally don’t think about “state”"

Similar presentations


Ads by Google