Lambdas and Streams. Functional interfaces Functional interfaces are also known as single abstract method (SAM) interfaces. Package java.util.function.

Slides:



Advertisements
Similar presentations
Java 8 Stream API Raj Thavamani Application Developer / Java Group Biomedical Informatics.
Advertisements

Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
 Both System.out and System.err are streams—a sequence of bytes.  System.out (the standard output stream) displays output  System.err (the standard.
C++ How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
VBA Modules, Functions, Variables, and Constants
Slides prepared by Rose Williams, Binghamton University Chapter 14 Generics and the ArrayList Class.
Using ArrayList. Lecture Objectives To understand the foundations behind the ArrayList class Explore some of the methods of the ArrayList class.
1 Chapter 2 Introductory Programs. 2 Getting started To create and run a Java program –Create a text file with a.java extension for the source code. For.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 10 *Arrays with more than one dimension *Java Collections API.
C++ Programming: Program Design Including Data Structures, Second Edition Chapter 22: Standard Template Library (STL)
Lesson 6 Functions Also called Methods CS 1 Lesson 6 -- John Cole1.
Lecture 2: Design and Implementation of Lambda Expressions in Java 8 Alfred V. Aho CS E6998-1: Advanced Topics in Programming Languages.
 2006 Pearson Education, Inc. All rights reserved Generics.
Chapter 10 2D Arrays Collection Classes. Topics Arrays with more than one dimension Java Collections API ArrayList Map.
Java Methods By J. W. Rider. Java Methods Modularity Declaring methods –Header, signature, prototype Static Void Local variables –this Return Reentrancy.
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,
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Copyright © 2012 Pearson Education, Inc. Chapter 6: Functions.
5-Aug-2002cse Arrays © 2002 University of Washington1 Arrays CSE 142, Summer 2002 Computer Programming 1
 2005 Pearson Education, Inc. All rights reserved. 1 Methods Called functions or procedures in other languages Modularize programs by separating its tasks.
Utilities (Part 2) Implementing static features 1.
Generics and Collections. Introduction Generics New feature of J2SE 5.0 Provide compile-time type safety Catch invalid types at compile time Generic methods.
Android How to Program, 2/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Methods in Java. Program Modules in Java  Java programs are written by combining new methods and classes with predefined methods in the Java Application.
Functions Top-down design Breaking a complex problem into smaller parts that we can understand is a common practice. The process of subdividing a problem.
Introduction to LINQ Chapter 11. Introduction Large amounts of data are often stored in a database—an organized collection of data. A database management.
Java™ How to Program, 10/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Visual C# 2012 for Programmers © by Pearson Education, Inc. All Rights Reserved.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Templates.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
1 Methods Introduction to Methods Passing Arguments to a Method More About Local Variables Returning a Value from a Method Problem Solving with Methods.
Java™ How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
CSCI 3327 Visual Basic Chapter 8: Introduction to LINQ and Collections UTPA – Fall 2011.
©SoftMoore ConsultingSlide 1 Generics “Generics constitute the most significant change in the Java programming language since the 1.0 release.” – Cay Horstmann.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 6 Arrays.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 6 Functions.
Java8 Released: March 18, Lambda Expressions.
IAP C# 2011 Lecture 2: Delegates, Lambdas, LINQ Geza Kovacs.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 6: Functions.
Java How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
Lecture 4 – Function (Part 1) FTMK, UTeM – Sem /2014.
Arrays (part 2) 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
Programming Fundamentals Enumerations and Functions.
Chapter 6 Functions. 6-2 Topics 6.1 Modular Programming 6.2 Defining and Calling Functions 6.3 Function Prototypes 6.4 Sending Data into a Function 6.5.
Lambdas and Streams. Stream manipulation Class Employee represents an employee with a first name, last name, salary and department and provides methods.
(C) 2010 Pearson Education, Inc. All rights reserved. Java How to Program, 8/e.
Chapter 11.  Large amounts of data are often stored in a database—an organized collection of data.  A database management system (DBMS) provides mechanisms.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Lecture 7: Arrays Michael Hsu CSULA 3 Opening Problem Read one hundred numbers, compute their average, and find out how many numbers are above the average.
Lambdas & Streams Laboratory
Taking Java from purely OOP by adding “functional level Programming”
Chapter 20 Generic Classes and Methods
Functional Processing of Collections (Advanced)
Java Algorithms.
Functional Programming with Java
14 The Stream API.
Introduction to LINQ Chapter 11 10/28/2015 Lect 4 CT1411.
Chapter 6 Methods: A Deeper Look
6 Chapter Functions.
Introduction to LINQ Chapter 11.
Functional interface.
A few of the more significant changes and additions. James Brucker
Lambda Expressions.
Object Oriented Programming in java
„Lambda expressions, Optional”
Corresponds with Chapter 5
Presentation transcript:

Lambdas and Streams

Functional interfaces Functional interfaces are also known as single abstract method (SAM) interfaces. Package java.util.function Six basic functional interfaces Many specialized versions of the basic functional interfaces Use with int, long and double primitive values. Also generic customizations of Consumer, Function and Predicate for binary operations—methods that take two arguments.

Built-in Functional interfaces

Built-in Functional interfaces (Cont’d)

Lambda Expressions Lambda expression anonymous method shorthand notation for implementing a functional interface. The type of a lambda is the type of the functional interface that the lambda implements. It can be used anywhere functional interfaces are expected.

Lambda Expressions (Cont’d) A lambda consists of a parameter list followed by the arrow token and a body, as in: ( parameterList ) -> { statements } The following lambda receives two int s and returns their sum: ( int x, int y) -> { return x + y;} A lambda’s parameter types may be omitted, as in: (x, y) -> { return x + y;} in which case, the parameter and return types are determined by the lambda’s context.

Lambda Expressions (Cont’d) A lambda with a one-expression body can be written as: (x, y) -> x + y In this case, the expression’s value is implicitly returned. When the parameter list contains only one parameter, the parentheses may be omitted, as in: value -> System.out.printf( "%d ", value) A lambda with an empty parameter list is defined with (), as in: () -> System.out.println( "Welcome to lambdas!" ) There are also specialized shorthand forms of lambdas that are known as method references.

Streams are objects that implement interface Stream from the package java.util.stream Enable you to perform functional programming tasks Specialized stream interfaces for processing int, long or double values Streams move elements through a sequence of processing steps—known as a stream pipeline Pipeline begins with a data source,  performs various intermediate operations and  ends with a terminal operation. A stream pipeline is formed by chaining method calls.

Streams (Cont’d) Streams do not have their own storage Once a stream is processed, it cannot be reused, because it does not maintain a copy of the original data source. An intermediate operation specifies tasks to perform on the stream’s elements and always results in a new stream. Intermediate operations are lazy they aren’t performed until a terminal operation is invoked. Terminal operation initiates processing of a stream pipeline’s intermediate operations producing a result

Common Intermediate Stream Operations

Common Terminal Stream Operations

Common Terminal Stream Operations (Cont’d)

IntStream Operations IntStream is a specialized stream for manipulating int values. Refer to IntStreamDemo Eclipse project The techniques shown in the example also apply to LongStream and DoubleStream objects for  long and double values, respectively IntStream static method of receives an int array and returns an IntStream for processing the array’s values.

IntStream Operations (Cont’d) IntStream method forEach (a terminal- operation) receives as its argument an object implementing the IntConsumer functional interface  This interface’s accept method receives one int value and  performs a task with it. Compiler can infer the types of a lambda’s parameters and the type returned by a lambda from the context in which the lambda is used. The parameter names and variable names that you use in lambdas cannot be the same as any other local variables in the lambda’s lexical scope;

IntStream Operations (Cont’d) Class IntStream provides terminal operations for common stream reductions count returns the number of elements min returns the smallest int max returns the largest int sum returns the sum of all the int s average returns an OptionalDouble (package java.util ) Class OptionalDouble ’s getAsDouble method returns the double in the object or throws a NoSuchElementException. To prevent this exception, you can call method orElse, which returns the OptionalDouble ’s value if there is one, or the value you pass to orElse, otherwise. Refer to OptionalDemo Eclipse project

IntStream Operations (Cont’d) IntStream method summaryStatistics performs the count, min, max, sum and average operations in one pass and returns the results as an IntSummaryStatistics object. You can define your own reductions for an IntStream by calling its reduce method. First argument is a value that helps you begin the reduction operation Second argument is an object that implements the  IntBinaryOperator functional interface Method reduce ’s first argument is formally called an identity value a value that, when combined with any stream element  using the IntBinaryOperator produces that element’s original value.

IntStream Operations (Cont’d) Filter elements to produce a stream of intermediate results that match a predicate. IntStream method filter receives an object that implements the IntPredicate functional interface. IntStream method sorted (a lazy operation) orders the elements of the stream into ascending order (by default). All prior intermediate operations in the stream pipeline must be complete  so that method sorted knows which elements to sort.

IntStream Operations (Cont’d) Mapping is an intermediate operation that transforms a stream’s elements to new values and produces a stream containing the resulting (possibly different type) elements. IntStream method map (a stateless intermediate operation) receives an object that implements the IntUnaryOperator functional. IntStream methods range and rangeClosed each produces an ordered sequence of int values.

Stream manipulation (Cont’d) Class Array ’s stream method is used to create a Stream from an array of objects. Stream method sorted sorts a stream’s elements into ascending order by default. To create a collection containing a stream pipeline’s results, you can use Stream method collect (a terminal operation). As the stream pipeline is processed, method collect performs a  mutable reduction operation that places the results into an object,  such as a List, Map or Set. Class Collectors provides static method toList That transforms a Stream into a List collection.

Stream manipulation (Cont’d) Stream method filter receives a Predicate and results in a stream of objects that match the Predicate. Predicate method test returns a boolean indicating whether the argument satisfies a condition. Interface Predicate also has methods and, negate and or. Refer to StreamInteger Eclipse project

Stream manipulation Stream method map maps each element to a new value and produces a new stream with the same number of elements as the original stream. A method reference is a shorthand notation for a lambda expression. ClassName :: instanceMethodName represents a method reference for an instance method of a class. Creates a one-parameter lambda that  invokes the instance method on the lambda’s argument and  returns the method’s result.

Stream manipulation (Cont’d) Stream method sorted can receive a Comparator to specify how to compare stream elements for sorting. By default, method sorted uses the natural order for the stream’s element type. For String s, the natural order is case sensitive, which means that "Z" is less than "a". Passing Comparator String.CASE_INSENSITIVE_ORDER performs a case-insensitive sort.