Streams.

Slides:



Advertisements
Similar presentations
Intro to Scala Lists. Scala Lists are always immutable. This means that a list in Scala, once created, will remain the same.
Advertisements

Java Review Interface, Casting, Generics, Iterator.
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.
EMT 2390L Lecture 4 Dr. Reyes Reference: The Linux Command Line, W.E. Shotts.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Loops in Scheme, II c. Kathi Fisler, 2001 (early slides assume map/filter)
Loops Notes adapted from Dr. Flores. It repeats a set of statements while a condition is true. while (condition) { execute these statements; } “while”
©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.
Grep, comm, and uniq. The grep Command The grep command allows a user to search for specific text inside a file. The grep command will find all occurrences.
Chapter 17 Java SE 8 Lambdas and Streams
Lambdas and Streams. Functional interfaces Functional interfaces are also known as single abstract method (SAM) interfaces. Package java.util.function.
Java Quiz Bowl A fun review of the Java you should know from CMPT 201 If you don’t know the answers - this week is for you to study up!
Introduction to Computation and Problem Solving Class 9: Static Methods and Data Members Prof. Steven R. Lerman and Dr. V. Judson Harward.
Problem Solving using the Java Programming Language May 2010 Mok Heng Ngee Day 5: Arrays.
Chapter 9: Perl Programming Practical Extraction and Report Language Some materials are taken from Sams Teach Yourself Perl 5 in 21 Days, Second Edition.
Topic 4:Subroutines CSE2395/CSE3395 Perl Programming Learning Perl 3rd edition chapter 4, pages 56-72, Programming Perl 3rd edition pages 80-83,
This recitation 1 An interesting point about A3: Using previous methods to avoid work in programming and debugging. How much time did you spend writing.
Georgia Institute of Technology What is new in Java 5.0 (1.5)? Barb Ericson Georgia Institute of Technology June 2006.
©SoftMoore ConsultingSlide 1 Generics “Generics constitute the most significant change in the Java programming language since the 1.0 release.” – Cay Horstmann.
ICS3U_FileIO.ppt File Input/Output (I/O)‏ ICS3U_FileIO.ppt File I/O Declare a file object File myFile = new File("billy.txt"); a file object whose name.
Java8 Released: March 18, Lambda Expressions.
1 CSC 2053 New from AutoBoxing 3 Before J2SE 5.0, working with primitive types required the repetitive work of converting between the primitive.
Java Methods 11/10/2015. Learning Objectives  Be able to read a program that uses methods.  Be able to write a write a program that uses methods.
IAP C# 2011 Lecture 2: Delegates, Lambdas, LINQ Geza Kovacs.
CMSC 202 Containers and Iterators. Container Definition A “container” is a data structure whose purpose is to hold objects. Most languages support several.
Arrays (part 2) 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
Uniq The uniq command is useful when you need to find duplicate lines in a file. The basic format of the command is uniq in_file out_file In this format,
JAVA 8 AND FUNCTIONAL PROGRAMMING. What is Functional Programming?  Focus on Mathematical function computations  Generally don’t think about “state”
Mid-Year Review. Coding Problems In general, solve the coding problems by doing it piece by piece. Makes it easier to think about Break parts of code.
Lambdas and Streams. Stream manipulation Class Employee represents an employee with a first name, last name, salary and department and provides methods.
Chapter 5 – Part 3 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved2/19 Outline The if Statement and Conditions Other Conditional.
12-CRS-0106 REVISED 8 FEB 2013 CSG2H3 Object Oriented Programming.
Quiz 3 Topics Functions – using and writing. Lists: –operators used with lists. –keywords used with lists. –BIF’s used with lists. –list methods. Loops.
Functional Processing of Collections (Advanced) 6.0.
1 M255 Object-oriented programming with Java Prepared By: Prof. Dr. Shehab Gamalel-Din Unit 10 Collections: Sets & Maps.
Lambdas & Streams Laboratory
String and Lists Dr. José M. Reyes Álamo.
CS314 – Section 5 Recitation 10
Functional Programming and Stream API
Taking Java from purely OOP by adding “functional level Programming”
Software Development Java Collections
Functional Processing of Collections (Advanced)
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.
The Linux Command Line Chapter 6
Generics and Type Parameters
Writing Methods AP Computer Science A.
L3. Necessary Java Programming Techniques
L3. Necessary Java Programming Techniques
© A+ Computer Science - Arrays and Lists © A+ Computer Science -
String and Lists Dr. José M. Reyes Álamo.
Barb Ericson Georgia Institute of Technology June 2006
Collections James Brucker.
(early slides assume map/filter)
Effective Java, 3rd Edition Chapter 7: Lambdas and Streams
Manipulating Pictures, Arrays, and Loops
slides created by Ethan Apter
Arrays.
Interator and Iterable
A few of the more significant changes and additions. James Brucker
Computer Science 312 Composing Functions Streams in Java 1.
Object Oriented Programming
Computer Science 312 Lambdas in Java 1.
Computer Science 312 What’s New in Java 8? 1.
Lambda Expressions.
Abstract Method & Abstract Classes
Drawing complex figures
Creating and Modifying Text part 3
Review for Midterm 3.
Java’s Stream API.
Presentation transcript:

Streams

Conceptual view of stream processing Two common patterns for working with collection of data: Supplier (source) Supplier (source) Filter Filter Map/Extract info Map/Extract info Consume Result Group & Collect

A Stream of data a stream of values a stream of values The values flow like a stream of data... Supplier (source) Supplier (source) a stream of values Filter Filter a stream of values Map/Extract info Map/Extract info Consume Result Group & Collect

Linux example using pipes cat Output all the lines in a file. grep -v Remove lines beginning with #. sort Sort the lines. uniq Eliminate duplicate lines. > file Write to a new file. $ cat somefile | grep -v '^#' | sort | uniq > outfile Pipe connects output from one command to input of the next command.

Java List Processing Suppose we have a list of Strings. Print all of them. Using forEach and Consumer: List<String> fruit = getFruits(); for(String name: fruit) { System.out.println( name ); } List<String> fruit = getFruits(); fruit.forEach( (x)->System.out.println(x) ); Consumer written as a Lambda expression

Explanation Every Collection and Iterable has a forEach( ) method. Consumer is an interface with 1 abstract method. It "consumes" the argument (returns nothing). // give each element to a "Consumer" list.forEach( Consumer<String> consumer ); interface Consumer<T> { public void accept(T arg); }

Streams Collection has 2 new methods for creating Streams. Stream is an interface for stream processing.

Streams Use a Stream to process elements List<String> fruit = Arrays.asList( "Apple", "Banana", "orange", "pear"); fruit.stream()._________ Add operations on the stream to do what you want

Stream methods Stream methods mostly return another Stream. Use to build pipelines: list.stream().filter( p ).map( f ). forEach "consumes" the Stream so it returns nothing filter( Predicate test ): Stream map( Function<T,R> fcn ): Stream<R> sorted( Comparator<T> ): Stream limit( maxSize ): Stream peek( Consumer ): Stream collect( Collector<T,A,R> ): R forEach( Consumer ): void

Composing Streams Predicate test(arg: T): bool Consumer Since Stream methods return another Stream, we can "chain" them together. Like a pipeline. Example: find all the fruit that end with "berry". What we want: fruit.stream() .filter( ends with "berry" ).forEach( print ) <<interface>> Predicate test(arg: T): bool <<interface>> Consumer accept(T): void

Writing and using lambda Write some Lambdas for the Predicate and Consumer Predicate<String> berries = (s) -> s.endsWith("berry"); Consumer<String> print = (s) -> System.out.println(s); // or, using a Method Reference System.out::println;

Assemble Parts of the Stream Now connect the parts to a Stream "pipeline": Predicate<String> berries = (s) -> s.endsWith("berry"); Consumer<String> print = (s) -> System.out.println(s); // Process the List of fruits: fruit.stream( ) .filter( berries ) .forEach( print );

Stream with Inline Lambda Don't have to declare type parameter (it is inferred). // Stream with Lambdas defined where used fruit.stream( ) .filter( (s) -> s.endsWith("berry") ) .forEach( System.out::println );

Stream with Collector Instead of consuming the Stream, collect the elements. Stream Filter Collect

Creating a New Collection Collect the stream result into a new collection (List) by using: stream.collect( Collector ). The Collectors class contains useful "collectors". We want Collectors.toList() List<String> result = fruit.stream() .filter(berries) .collect( Collectors.toList() ); Collector

Sort the Fruit & remove duplicates Using a loop and old-style Java is not so easy: List<String> fruit = getFruits(); Collections.sort( fruit ); String previous = ""; // can't modify list in a for-each loop // so use an indexed for loop for(int k=0; k<fruit.size(); ) { compare this fruit with previous fruit if same then remove it. Be careful about the index (k)! }

Sort the Fruit & remove duplicates Remove duplicate items from the list List<String> fruit = getFruits(); List<String> sortedFruit = fruit.stream() .sorted() .distinct() .collect( Collectors.toList() );

MoneyUtil.filterByCurrency Filter all the Valuable in the parameter (money) that have the requested currency: static <E extends Valuable> List<E> filterByCurrency(List<E> money,String currency){ return money.stream( ) .___________________________ }

Stream with Mapping Map one kind of value to another kind of value. Collect / Consume stream.map( Function<T,R> mapper ) T = type of input values (the stream type) R = type of output value (output stream type)

Get the student names For every student in class, get the student's name and put the names into a new List Function<Student,String> mapToName = s -> s.getName(); List<String> names = students.stream() .map( mapToName ) .collect( Collectors.toList() );

How to Sum Valuables? Can we use a Stream to sum all the valuables in a List? public double sumForCurrency( List<Valuable> money, String currency ) { double total = 0.0; for(Valuable v: money) { if ( v.getCurrency().equals(currency) ) total += v.getValue(); } return total;

Special Interfaces for Primitives ToDoubleFuntion, DoubleStream, for "double" primitive Stream MapToDouble DoubleStream stream.mapToDouble( ToDoubleFunction<T> f ) A ToDoubleFunction<T> maps T to "double". ToDoubleFunction<Valuable> getValue = v -> v.getValue(); // returns v.getValue()

Sum All Valables Can we use a Stream to sum all the valuables in a List? public double sumByCurrency( List<Valuable> money ) { double total = money.stream() .mapToDouble( Valuable::getValue ) .sum( ); // a method of DoubleStream return total; }

Sum for One Currency Can you sum money just for one currency, using a Stream? public double sumForCurrency( List<Valuable> money, String currency ) { return money .stream() .___________________________________ }

How to Sum Valuables? Can we use a Stream to sum all the valuables in a List? public double sumByCurrency( List<Valuable> money, String currency ) { double total = 0.0; for(Valuable v: money) { if ( v.getCurrency().equals(currency) ) total += v.getValue(); } return total;

How to Sum Valuables? Can we use a Stream to sum all the valuables in a List? public double sumByCurrency( List<Valuable> money, String currency ) { double total = 0.0; for(Valuable v: money) { if ( v.getCurrency().equals(currency) ) total += v.getValue(); } return total;

Exercise: get all currencies Use a stream to return the names of all currencies in a list of Valuable. Include each currency only once. List<String> getCurrencies(List<Valuable> money) { // .stream() // .map( Function<Valuable,String> ) // .distinct() // .sorted() // .collect( Collectors.toList() ) List<Valuable> money = Arrays.asList( new Coin(5,"Baht"), new Banknote(10,"Rupee"), new Coin(1,"Baht"), new Banknote(50,"Dollar")); List<String> currencies = getCurrencies(money); // should be: { "Baht", "Dollar", "Rupee" }

Exercise: try it Try to solve it yourself before looking at the next slide.

Exercise: get all currencies List<String> getCurrencies(List<Valuable> money) { List<String> result = money.stream( ) .map( (m) -> m.getCurrency() ) .distinct() // remove duplicates .sorted() .collect( Collectors.toList() ); return result; List<Valuable> money = Arrays.asList( new Coin(5,"Baht"), new Banknote(10,"Rupee"), new Coin(1,"Baht"), new Banknote(50,"Dollar")); List<String> currencies = getCurrencies(money); // result: { "Baht", "Dollar", "Rupee" }