Computer Science 312 Composing Functions Streams in Java 1.

Slides:



Advertisements
Similar presentations
Chapter 5: Abstraction, parameterization, and qualification Xinming (Simon) Ou CIS 505: Programming Languages Kansas State University Fall
Advertisements

1 Programming Languages (CS 550) Lecture Summary Functional Programming and Operational Semantics for Scheme Jeremy R. Johnson.
C# and LINQ Yuan Yu Microsoft Research Silicon Valley.
MATHEMATICAL FOUNDATIONS SUPPLEMENTAL MATERIAL – NOT ON EXAM.
Text Chapters 1, 2. Sorting ä Sorting Problem: ä Input: A sequence of n numbers ä Output: A permutation (reordering) of the input sequence such that:
Slides prepared by Rose Williams, Binghamton University Chapter 11 Recursion.
UNIVERSITY OF SOUTH CAROLINA Department of Computer Science and Engineering Introduction to Functional Programming Notes for CSCE 190 Based on Sebesta,
PPL Syntax & Formal Semantics Lecture Notes: Chapter 2.
PPL Syntax & Formal Semantics Lecture Notes: Chapter 2.
Computer Science 209 The Strategy Pattern II: Emulating Higher-Order Functions.
Chapter 17 Java SE 8 Lambdas and Streams
HOW TO SOLVE IT? Algorithms. An Algorithm An algorithm is any well-defined (computational) procedure that takes some value, or set of values, as input.
Computer Science 111 Fundamentals of Programming I Search Algorithms.
Lambdas and Streams. Functional interfaces Functional interfaces are also known as single abstract method (SAM) interfaces. Package java.util.function.
Functional Programming Shane Carr CSE 232, September 4, 2015.
A review session 2013-T2 Lecture 16 School of Engineering and Computer Science, Victoria University of Wellington COMP 103 Marcus Frean.
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 19 : Recursion King Fahd University of Petroleum & Minerals College of Computer.
Lecture 2 Algorithm Analysis Arne Kutzner Hanyang University / Seoul Korea.
Examples using Arrays. Summing Squares Problem: To compute the sum of the squares of N numbers N is given N values are also given These should be read.
CSC 580 – Theory of Programming Languages, Spring, 2009 Week 9: Functional Languages ML and Haskell, Dr. Dale E. Parson.
Optimization in XSLT and XQuery Michael Kay. 2 Challenges XSLT/XQuery are high-level declarative languages: performance depends on good optimization Performance.
1Computer Sciences Department Princess Nourah bint Abdulrahman University.
Going Functional Primož Gabrijelčič. Functional programming.
Inside LINQ to Objects How LINQ to Objects work Inside LINQ1.
Java8 Released: March 18, Lambda Expressions.
1 FP Foundations, Scheme In Text: Chapter Chapter 14: FP Foundations, Scheme Mathematical Functions Def: A mathematical function is a mapping of.
CSCI 1100/1202 January 14, Abstraction An abstraction hides (or ignores) the right details at the right time An object is abstract in that we don't.
Haskell Chapter 5, Part II. Topics  Review/More Higher Order Functions  Lambda functions  Folds.
JAVA 8 AND FUNCTIONAL PROGRAMMING. What is Functional Programming?  Focus on Mathematical function computations  Generally don’t think about “state”
Merge Sort Comparison Left Half Data Movement Right Half Sorted.
Lambdas and Streams. Stream manipulation Class Employee represents an employee with a first name, last name, salary and department and provides methods.
Programming in Java (COP 2250) Lecture 12 & 13 Chengyong Yang Fall, 2005.
PPL Syntax & Formal Semantics Lecture Notes: Chapter 2.
Click to edit Master text styles Stacks Data Structure.
CS 116 Object Oriented Programming II Lecture 13 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
Functional Processing of Collections (Advanced) 6.0.
Lambdas & Streams Laboratory
Lecture 2 Algorithm Analysis
CS314 – Section 5 Recitation 10
Chapter 4 Repetition Statements (loops)
An Iterative FFT We rewrite the loop to calculate nkyk[1] once
Functional Programming and Stream API
Chapter 2 (16M) Sorting and Searching
{ XML Technologies } BY: DR. M’HAMED MATAOUI
The Strategy Pattern II: Emulating Higher-Order Functions
Functional Processing of Collections (Advanced)
Aggregation Aggregations operations process data records and return computed results. Aggregation operations group values from multiple documents together,
Chapter 15 QUERY EXECUTION.
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.
Chapter 8: Collections: Arrays
Streams.
Chapter 7 Stack.
COS 260 DAY 10 Tony Gauvin.
© A+ Computer Science - Arrays and Lists © A+ Computer Science -
STL - Algorithms.
Building Java Programs Chapter 19
Building Java Programs Chapter 19
Revised based on textbook author’s notes.
Computer Science 312 Lambdas in Java 1.
Collectors and Terminal Operations
Computer Science 312 What’s New in Java 8? 1.
More Stream Processing
Lambda Expressions.
The structure of programming
Lazy Evaluation CSCE 314: Programming Languages Dr. Dylan Shell
Introduction to Computer Science
Higher-Order Functions in Haskell
Intro to Computer Science CS1510 Dr. Sarah Diesburg
functions are also data! other functions as input!
Presentation transcript:

Computer Science 312 Composing Functions Streams in Java 1

Composing Functions into a Pipeline In Haskell: rightToLeftComposition x = f (g x) rightToLeftComposition x = f $ g $ x rightToLeftComposition = f . g $ is the apply operator (does left to right without parentheses) . is the composition operator (builds a new function)

Composing Comparisons for sort By ascending order of weight: inventory.sort(comparing(Apple::getWeight));

Composing Comparisons for sort By descending order of weight: inventory.sort(comparing(Apple::getWeight).reversed());

Composing Comparisons for sort By descending order of weight, and then by country if they have the same weight: inventory.sort(comparing(Apple::getWeight) .reversed() .thenComparing(Apple::getCountry));

Composing Predicates Can negate a predicate: Predicate<Apple> notRedApple = redApple.negate();

Composing Predicates Can negate a predicate: Can AND two predicates: Predicate<Apple> notRedApple = redApple.negate(); Predicate<Apple> redAndHeavyApple = redApple.and(a -> a.getWeight() > 150);

Composing Predicates Can negate a predicate: Can AND two predicates: Can OR two predicates: Predicate<Apple> notRedApple = redApple.negate(); Predicate<Apple> redAndHeavyApple = redApple.and(a -> a.getWeight() > 150); Predicate<Apple> redAndHeavyOrMacintoshApple = redApple.and(a -> a.getWeight() > 150) .or(a -> a.getType() == MACINTOSH);

Composing Functions Use andThen to compose two functions for left- to-right pipelining T is the argument type of f1 and U is the result type of f2 The result type of f1 must match the argument type of f2 Function<T, U> pipelinedF = f1.andThen(f2);

Pipelined Functions Example public class Letter{ public static String addHeader(String text){ return "From Raoul, Mario and Alan: " + text; } public static String addFooter(String text){ return text + " Kind regards"; public static String checkSpelling(String text){ return text.replaceAll("labda", "lambda");

Pipelined Functions Example Function<String, String> addHeader = Letter::addHeader; Function<String, String> transformationPipeline = addHeader.andThen(Letter::checkSpelling) .andThen(Letter::addFooter); Functions are chained and evaluated from left to right

andThen vs compose Use andThen for left-to-right composition: Use compose for right-to-left composition:

What Are Streams? A stream is an abstraction of a sequence of data Each data value is provided on demand Unlike collections, streams can be lazy (even infinite) Like video streaming vs a DVD

Streams vs Collections Collections are used to store and manage data Streams are used to process these data Stream processing Hides procedural details of iteration Supports optimizations like parallel processing

Example: Get the Names of Low Calorie Dishes

Example: Get the Names of Low Calorie Dishes

What’s Needed for Data Processing A data source on which to open a stream A set of intermediate operations to transform these data (map, filter, sorted, etc.) A terminal operation (collect, count, etc.) to collect the results

Get Source, Process, and Collect Print the names of the first three high-calorie dishes

Get Source, Process, and Collect

Internal vs External Iteration The for loop over a collection is an example of external iteration Must visit every item in an eager manner Streams support internal iteration Visit items in a lazy manner, only as needed Intermediate operations can be merged as their results are collected by the terminal operation Processing can be parallelized

Which Operations Are Intermediate and Which Are Terminal? long count = menu.stream() .filter(d -> d.getCalories() > 300) .distinct() .limit(3) .count();

Parallelize! sortedBigData = bigData.parallelStream() .sorted() .collect(toList());

Intermediate operations Chapter 5 For next time Intermediate operations Chapter 5