Taking Java from purely OOP by adding “functional level Programming”

Slides:



Advertisements
Similar presentations
Spring Semester 2013 Lecture 5
Advertisements

Road Map Introduction to object oriented programming. Classes
Lecture 2: Design and Implementation of Lambda Expressions in Java 8 Alfred V. Aho CS E6998-1: Advanced Topics in Programming Languages.
Java Methods By J. W. Rider. Java Methods Modularity Declaring methods –Header, signature, prototype Static Void Local variables –this Return Reentrancy.
Comp 248 Introduction to Programming Chapter 4 - Defining Classes Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
Lambdas and Streams. Functional interfaces Functional interfaces are also known as single abstract method (SAM) interfaces. Package java.util.function.
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.
Chapter 06 (Part I) Functions and an Introduction to Recursion.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
Introduction to c++ programming - object oriented programming concepts - Structured Vs OOP. Classes and objects - class definition - Objects - class scope.
2-Dec-15 Inner Classes. 2 Inner classes All the classes so far have been “top level” It is possible (and useful) to define a class inside another class.
“Education is a Treasure that follows you everywhere.” – Chines Proverb Methods and Functions.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 9 Java Fundamentals Objects/ClassesMethods Mon.
Java8 Released: March 18, Lambda Expressions.
IAP C# 2011 Lecture 2: Delegates, Lambdas, LINQ Geza Kovacs.
MIT-AITI: Functions Defining and Invoking Functions Functions as Data Function Scope: The call Object Function Arguments: The arguments objects Function.
Java How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Methods.
JAVA 8 AND FUNCTIONAL PROGRAMMING. What is Functional Programming?  Focus on Mathematical function computations  Generally don’t think about “state”
CSE 501N Fall ‘09 03: Class Members 03 September 2009 Nick Leidenfrost.
(C) 2010 Pearson Education, Inc. All rights reserved. Java How to Program, 8/e.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Functional Processing of Collections (Advanced) 6.0.
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.
Arrays Chapter 7.
Inner Classes.
Inner Classes 27-Dec-17.
Functional Programming
Information and Computer Sciences University of Hawaii, Manoa
Definition of the Programming Language CPRL
Advanced Java Programming 51037
Classes (Part 1) Lecture 3
Java Primer 1: Types, Classes and Operators
Methods Chapter 6.
Chapter 20 Generic Classes and Methods
Functions, locals, parameters, and separate compilation
Generics, Lambdas, Reflections
Functional Processing of Collections (Advanced)
Methods.
Java Algorithms.
Functional Programming with Java
Chapter 6 Arrays.
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.
Object Based Programming
Chapter 9 Inheritance and Polymorphism
Chapter 6 Methods: A Deeper Look
Java Programming Language
COS 260 DAY 10 Tony Gauvin.
Introducing Arrays Array is a data structure that represents a collection of the same types of data.
Group Status Project Status.
CHAPTER 6 GENERAL-PURPOSE METHODS
Generic programming in Java
Defining methods and more arrays
Constructors and Other Tools
Functional interface.
BBIT 212/ CISY 111 Object Oriented Programming (OOP)
Chapter 6 Arrays.
A few of the more significant changes and additions. James Brucker
Generics, Lambdas, Reflections
Computer Science 312 What’s New in Java 8? 1.
Lambda Expressions.
Inner Classes 11-May-19.
Inner Classes 18-May-19.
Review for Midterm 3.
„Lambda expressions, Optional”
Corresponds with Chapter 5
Generics, Lambdas and Reflection
Java’s Stream API.
Inner Classes 25-Oct-19.
Presentation transcript:

Taking Java from purely OOP by adding “functional level Programming” Lambda Expression Introduced in Java 8 Taking Java from purely OOP by adding “functional level Programming”

Outline What is functional programming? What are the benefits of functional programming? Functional programming in Java 8 Java 8 lambda expressions Implementation of Java 8 lambda expressions Streams Modified from www.cs.columbia.edu/~aho/cs6998

What is Functional Programming? treats computation as the evaluation of mathematical functions Functions can take functions as arguments and return functions as results Prefers recursion over explicit for-loops

Why do Functional Programming? Allows us to write easier-to-understand, more declarative, more concise programs than imperative programming Allows us to focus on the problem rather than the code Facilitates parallelism Less overhead than Classes/Objects

Example of a Lambda Expression The lambda expression (from lamba calculus) λ x . (+ x 1) 2 represents the application of a function λ x . (+ x 1) with a formal parameter x and a body + x 1 to the argument 2. Notice that the function definition λ x . (+ x 1) has no name; it is an anonymous function. In Java 8, we would represent this function definition by the Java 8 lambda expression x -> x + 1.

More Examples of Java 8 Lambdas A Java 8 lambda is basically a method in Java without a declaration usually written as (parameters) -> { body }. Examples, (int x, int y) -> { return x + y; } x -> x * x ( ) -> x A lambda can have zero or more parameters separated by commas and their type can be explicitly declared or inferred from the context. Parenthesis are not needed around a single parameter –otherwise are required. ( ) is used to denote zero parameters. The body can contain zero or more statements. Braces are not needed around a single-statement body. All braches of the body of code must return a value Note: return type of the “expression”/”function” is not declared

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 major programming languages already have support for lambda expressions A big challenge was to introduce lambdas without requiring recompilation of existing binaries

Benefits of Lambdas in Java 8 Enabling functional programming Writing leaner more compact code Facilitating parallel programming Developing more generic, flexible and reusable APIs Being able to pass behaviors as well as data to functions

Java 8 Lambdas – more details Syntax of Java 8 lambda expressions Functional interfaces Variable capture Method references Default methods

Example: Print list of integers using lambda expression Special Note: List is an interface, so intSeq is actually an ArrayList instance and it is ArrayList that has the forEach method defined. List<Integer> intSeq = Arrays.asList(1,2,3); intSeq.forEach(x -> System.out.println(x)); x -> System.out.println(x) is a lambda expression that defines an anonymous function with one parameter named x of type Integer Here the action to execute is represented by the lambda expression/anonymous function List<Integer> is a parameterized type, parameterized by the type argument <Integer> the Arrays.asList method returns a fixed-size list backed by an array; it can take “vararg” arguments forEach is a method that takes as input a function and calls the function for each value on the list Note the absence of type declarations in the lambda; the Java 8 compiler does type inference Java 8 is still statically typed Braces are not needed for single-line lambdas (but could be used if desired). Introduced in java 8 --- for most collection data class types like ArrayList, Vector etc, forEach( Consumer <? Super E> action)  a method that will execute the action for each element in the Collection of type E.

Example 2: A multiline lambda List<Integer> intSeq = Arrays.asList(1,2,3); intSeq.forEach(x -> { x += 2; System.out.println(x); }); Now adding 2 before printing out each element in List Note: braces are needed to enclose a multiline lambda expression braces needed to enclose a multiline lambda expression

Example 3: A lambda with a defined local variable List<Integer> intSeq = Arrays.asList(1,2,3); intSeq.forEach(x -> { int y = x * 2; System.out.println(y); }); you can define local variables inside the body of a lambda expression Just as with ordinary functions, you can define local variables inside the lambda expression

Example 4: A lambda with a declared parameter type List<Integer> intSeq = Arrays.asList(1,2,3); intSeq.forEach((Integer x) -> { x += 2; System.out.println(x); }); if you wish, specify the parameter type EXPLICITLY –however, the compiler can in this case infer the type of the parameter x. You can, if you wish, specify the parameter type The compiler knows the type of intSeq is a list of Integers Since the compiler can do type inference, you don’t need to specify the type of x.

Implementation of Java 8 Lambdas compiler converts a lambda expression into a function then calls the generated function For example, x -> System.out.println(x) could be converted into a generated static function public static void genName(Integer x) { System.out.println(x); } Compiler must figure out: what type should be generated for this function? How should it be called? What class should it go in? What type should be generated for this function? How should it be called? What class should the translated lambda expression function be placed it? Should the generated method be a static or an instance method? The Java 8 designers spent a lot of time thinking about how to implement lambdas!

Functional Interfaces Java 8 lambdas are assigned to functional interfaces. A functional interface is a Java interface with exactly one non-default method. E.g., public interface Consumer<T> { void accept(T t); } The package java.util.function defines many new useful functional interfaces like the Consumer interface we saw used by the new forEach method of Collection classes: Functional interfaces are a common idiom in Java code. Examples of existing JDK functional interfaces: Runnable, Comparable<T>, Callable<V>. Design decision: Java 8 lambdas should work with existing Java code without requiring recompilation. RECALL Introduced in java 8 --- for most collection data class types like List, Vector etc, forEach( Consumer <? Super E> action)  a method that will execute the action for each element in the Collection of type E.

Assigning a Lambda to a Local Variable //”functional” interface defined in java.utils.functions (new to java 8) public interface Consumer<T> { void accept(T t); } //now inside some collection class like ArrayList or Vector void forEach(Consumer<Integer> action { for (Integer i:items) { action.accept(t); //now inside your code List<Integer> intSeq = Arrrays.asList(1,2,3); //define your lambda expression on right and assign to variable cnsmr Consumer<Integer> cnsmr = x -> System.out.println(x); intSeq.forEach(cnsmr); Here is an interface called Consumer with a single method called accept. The forEach method iterates through the items in the object Consumer and performs the action accept on each item. The lambda expression becomes the body of the function in the interface. The signature of the function is defined by the interface. Special Note: List is an interface, so intSeq is actually an ArrayList instance and it is ArrayList that has the forEach method defined.

Properties of the Generated Method The method generated from a Java 8 lambda expression has the same signature as the method in the functional interface The type is the same as that of the functional interface to which the lambda expression is assigned The lambda expression becomes the body of the method in the interface Any interface with only one nondefault method is considered a functional interface by Java 8. So functional interfaces are Java 8’s secret sauce for backward compatibility.

Variable Capture Lambdas can interact with variables defined outside the body of the lambda Using these variables is called variable capture

Local Variable Capture Example public class LVCExample { public static void main(String[] args) { List<Integer> intSeq = Arrays.asList(1,2,3); int var = 10; intSeq.forEach(x -> System.out.println(x + var)); } Note: local variables used inside the body of a lambda must be final or effectively final This lambda “captures” the variable var. Lambda expression

Static Variable Capture Example public class SVCExample { private static int var = 10; public static void main(String[] args) { List<Integer> intSeq = Arrays.asList(1,2,3); intSeq.forEach(x -> System.out.println(x + var)); } Can access statically defined variables too

Method References – short cut to writing lambda expressions Method references can be used to pass an existing function in places where a lambda is expected The signature of the referenced method needs to match the signature of the functional interface method

Summary of Method References Method Reference Type Syntax Example static ClassName::StaticMethodName String::valueOf constructor ClassName::new ArrayList::new specific object instance objectReference::MethodName x::toString arbitrary object of a given type ClassName::InstanceMethodName Object::toString

Conciseness with Method References We can rewrite the statement intSeq.forEach(x -> System.out.println(x)); more concisely using a method reference intSeq.forEach(System.out::println);

Default Methods https://www.youtube.com/watch?v=MLksirK9nnE Java 8 uses lambda expressions and default methods in conjunction with the Java collections framework to achieve backward compatibility with existing published interfaces For a full discussion see Brian Goetz, Lambdas in Java: A peek under the hood. https://www.youtube.com/watch?v=MLksirK9nnE

Stream API – in Java 8 Stream<T> stream = collection.stream(); The new java.util.stream package provides utilities to support functional-style operations on streams of values. A common way to obtain a stream is from a collection: Stream<T> stream = collection.stream(); Streams can be sequential or parallel. Streams are useful for selecting values and performing actions on the results.

Stream Operations An intermediate operation keeps a stream open for further operations. Intermediate operations are lazy. A terminal operation must be the final operation on a stream. Once a terminal operation is invoked, the stream is consumed and is no longer usable.

Example Intermediate Operations filter excludes all elements that don’t match a Predicate. map performs a one-to-one transformation of elements using a Function.

A Stream Pipeline A stream pipeline has three components: A source such as a Collection, an array, a generator function, or an IO channel; Zero or more intermediate operations; and A terminal operation

Stream Example int sum = widgets.stream() .filter(w -> w.getColor() == RED) .mapToInt(w -> w.getWeight()) .sum(); widgets is a Collection<Widget>. created a stream of Widget objects via Collection.stream(), filter it to produce a stream containing only the red widgets, transform it into a stream of int values representing the weight of each red widget. stream is summed to produce a total weight. Methods filter, mapToInt are examples of Intermediate operations Method sum is a terminal operation

Last Example: Using lambdas and stream to sum the squares of the elements on a list List<Integer> list = Arrays.asList(1,2,3); int sum = list.stream().map(x -> x*x).reduce((x,y) -> x + y).get(); System.out.println(sum); Here map(x -> x*x) squares each element and then reduce((x,y) -> x + y) reduces all elements into a single number http://viralpatel.net/blogs/lambda-expressions-java-tutorial/

References The Java Tutorials, http://docs.oracle.com/javase/tutorial/java/index.html Lambda Expressions, http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html Adib Saikali, Java 8 Lambda Expressions and Streams, www.youtube.com/watch?v=8pDm_kH4YKY Brian Goetz, Lambdas in Java: A peek under the hood. https://www.youtube.com/watch?v=MLksirK9nnE