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

Slides:



Advertisements
Similar presentations
Higher-Order Functions and Loops c. Kathi Fisler,
Advertisements

Java 8 Stream API Raj Thavamani Application Developer / Java Group Biomedical Informatics.
Week 9: Methods 1.  We have written lots of code so far  It has all been inside of the main() method  What about a big program?  The main() method.
16-Jun-15 Recursion. 2 Definitions I A recursive definition is a definition in which the thing being defined occurs as part of its own definition Example:
Introducing Loop Statements Liang, pages Loop statements control repeated execution of a block of statements Each time the statements in the block.
©2004 Brooks/Cole Chapter 8 Arrays. Figures ©2004 Brooks/Cole CS 119: Intro to JavaFall 2005 Sometimes we have lists of data values that all need to be.
28-Jun-15 Recursion. 2 Definitions I A recursive definition is a definition in which the thing being defined occurs as part of its own definition Example:
Lecture 2: Design and Implementation of Lambda Expressions in Java 8 Alfred V. Aho CS E6998-1: Advanced Topics in Programming Languages.
Programming with Collections Grouping & Looping - Collections and Iteration Week 7.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Repetition Statements.
C++ Functions. 2 Agenda What is a function? What is a function? Types of C++ functions: Types of C++ functions: Standard functions Standard functions.
Computer Science 209 The Strategy Pattern II: Emulating Higher-Order Functions.
Chapter 17 Java SE 8 Lambdas and Streams
Appendix B: Lambda Expressions In the technical keynote address for JavaOne 2013, Mark Reinhold, chief architect for the Java Platform Group at Oracle,
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Summary and Exam COMP 102.
Computer Science Standard Level Mastery Aspects. Mastery Item Claimed JustificationWhere Listed Arrays Used to store the student data Lines P.
Lambdas and Streams. Functional interfaces Functional interfaces are also known as single abstract method (SAM) interfaces. Package java.util.function.
Lists in Python.
CS 106 Introduction to Computer Science I 04 / 20 / 2007 Instructor: Michael Eckmann.
Functional Programming Think Differently!! Functional languages are expressive, accomplishing tasks using short, succinct and readable code. Functional.
CHAPTER 7 arrays I NTRODUCTION T O C OMPUTER P ROGRAMMING (CSC425)
Going Functional Primož Gabrijelčič. Functional programming.
Abstraction: Procedures as Parameters CMSC Introduction to Computer Programming October 14, 2002.
Practical Session 4 Java Collections. Outline Working with a Collection The Collection interface The Collection hierarchy Case Study: Undoable Stack The.
Grouping objects Iterators. Iterator type Third variation to iterate over a collection Uses a while loop and Iterator object But NO integer index variable.
Inside LINQ to Objects How LINQ to Objects work Inside LINQ1.
JAVA COLLECTIONS LIBRARY School of Engineering and Computer Science, Victoria University of Wellington COMP T2, Lecture 2 Thomas Kuehne.
Java8 Released: March 18, Lambda Expressions.
Recursion A recursive definition is one which uses the word or concept being defined in the definition itself Example: “A computer is a machine.
Functional Programming IN NON-FUNCTIONAL LANGUAGES.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Summary and Exam COMP 102.
Methods Awesomeness!!!. Methods Methods give a name to a section of code Methods give a name to a section of code Methods have a number of important uses.
Jeopardy Print Me Which loop? Call Me Name Me My Mistake Q $100 Q $200 Q $300 Q $400 Q $500 Q $100 Q $200 Q $300 Q $400 Q $500 Final Jeopardy.
Written by: Dr. JJ Shepherd
JavaScript Functions. CSS Inheritance Which formatting applies? x y z input { display: block; } input.pref { background:red; } If you have a selector.
Aggregator  Performs aggregate calculations  Components of the Aggregator Transformation Aggregate expression Group by port Sorted Input option Aggregate.
Collections and Iteration Week 13.  Collections  ArrayList objects  Using loops with collections Collections and Iteration CONCEPTS COVERED THIS WEEK.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
Visual C# 2005 Using Arrays. Visual C# Objectives Declare an array and assign values to array elements Initialize an array Use subscripts to access.
Lambdas and Streams. Stream manipulation Class Employee represents an employee with a first name, last name, salary and department and provides methods.
Lecture 9:FXML and Useful Java Collections Michael Hsu CSULA.
FUNCTIONS (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
Functional Processing of Collections (Advanced) 6.0.
CS 1428 Final Exam Review. Exam Format 200 Total Points – 60 Points Writing Programs – 45 Points Tracing Algorithms and determining results – 20 Points.
© 2004 Pearson Addison-Wesley. All rights reserved October 5, 2007 Arrays ComS 207: Programming I (in Java) Iowa State University, FALL 2007 Instructor:
Building Java Programs Chapter 19 Functional Programming with Java 8 Copyright (c) Pearson All rights reserved.
Lambdas & Streams Laboratory
CS314 – Section 5 Recitation 10
Advanced Java Programming 51037
Chapter 6: Using Arrays.
Functional Programming and Stream API
Taking Java from purely OOP by adding “functional level Programming”
5. Function (2) and Exercises
Recitation 11 Lambdas added to Java 8.
Functional Processing of Collections (Advanced)
JavaScript Functions.
Java Algorithms.
Functional Programming with Java
Java 8 Java 8 is the biggest change to Java since the inception of the language Lambdas are the most important new addition Java is playing catch-up: most.
For Monday Read WebCT quiz 18.
Streams.
Arrays We often want to organize objects or primitive data in a way that makes them easy to access and change. An array is simple but powerful way to.
CSC1018F: Intermediate Python
Chapter 7 The Java Array Object © Rick Mercer.
Python Tutorial for C Programmer Boontee Kruatrachue Kritawan Siriboon
Fundamentals of Functional Programming
A few of the more significant changes and additions. James Brucker
Computer Science 312 Composing Functions Streams in Java 1.
More Stream Processing
Lambda Expressions.
Presentation transcript:

JAVA 8 AND FUNCTIONAL PROGRAMMING

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

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

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

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

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

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);

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()); } });

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

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.

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

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

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

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

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

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);

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

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

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);

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()

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());