LAMBDA EXPRESSIONS. Summer 2018

Similar documents
Lambda Notes for CS 2102

Java Bytecode (binary file)

Lambdas in Java 8. Start programming in a more functional style

ANSWERS. Birkbeck (University of London) Software and Programming 1 In-class Test Feb Student Name Student Number. Answer all questions

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

Operators. Java operators are classified into three categories:

bitwise inclusive OR Logical logical AND && logical OR Ternary ternary? : Assignment assignment = += -= *= /= %= &= ^= = <<= >>= >>>=

Methods. Contents Anatomy of a Method How to design a Method Static methods Additional Reading. Anatomy of a Method

Language Reference Manual

APCS Semester #1 Final Exam Practice Problems

CT 229 Java Syntax Continued

CS 231 Data Structures and Algorithms, Fall 2016

Chapter 3: Operators, Expressions and Type Conversion

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

int j = 0, sum = 0; for (j = 3; j <= 79; j++) { sum = sum + j; System.out.println(sum); //Show the progress as we iterate thru the loop.

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 8: SEP. 29TH INSTRUCTOR: JIAYIN WANG

Interfaces CSC 123 Fall 2018 Howard Rosenthal

New Features in Java 8

PROGRAMMING FUNDAMENTALS

Java Technologies. Lecture IV. Valdas Rapševičius

Array Basics: Outline. Creating and Accessing Arrays. Creating and Accessing Arrays. Arrays (Savitch, Chapter 7)

Fontys Hogeschool voor Techniek en Logistiek. March 13, 2018

Every language has its own scoping rules. For example, what is the scope of variable j in this Java program?

Research Group. 2: More types, Methods, Conditionals

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 is going to get really

All copyrights reserved - KV NAD, Aluva. Dinesh Kumar Ram PGT(CS) KV NAD Aluva

Math Modeling in Java: An S-I Compartment Model

Flow of Control. Chapter 3 Part 3 The Switch Statement

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

Monad Background (3A) Young Won Lim 11/20/17

Java Methods. Lecture 8 COP 3252 Summer May 23, 2017

Java Primer 1: Types, Classes and Operators

Free your Lambdas Java SE 8

Program Fundamentals

Introduction to Computer Science Unit 2. Notes

CSE 142, Spring 2009, Sample Final Exam #2. Good luck!

Type Conversion. and. Statements

Motivating Examples (1.1) Selections. Motivating Examples (1.2) Learning Outcomes. EECS1022: Programming for Mobile Computing Winter 2018

Java Enum Java, winter semester ,2018 1

Selections. EECS1021: Object Oriented Programming: from Sensors to Actuators Winter 2019 CHEN-WEI WANG

School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

Function Literals and Type Inference. Lecture 14 Spring 2018 COMP110

Introduction to Programming Using Java (98-388)

Object Oriented Programming with Java

Object Oriented Programming Exception Handling

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods

STUDENT LESSON A12 Iterations

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

1 Introduction Java, the beginning Java Virtual Machine A First Program BlueJ Raspberry Pi...

Higher-Order Sequential Operations

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

C++ Arrays and Vectors

Review Chapter 6 in Bravaco. Short Answers 1. This type of method does not return a value. a. null b. void c. empty d. anonymous

Glossary. (Very) Simple Java Reference (draft, v0.2)

IEEE Floating-Point Representation 1

Key Differences Between Python and Java

ANSWERS. Birkbeck (University of London) Software and Programming 1 In-class Test Feb Student Name Student Number. Answer all questions

Binghamton University. CS-211 Fall Syntax. What the Compiler needs to understand your program

Computer Science II Lecture 1 Introduction and Background

CS125 : Introduction to Computer Science. Lecture Notes #6 Compound Statements, Scope, and Advanced Conditionals

LAMBDA EXPRESSIONS AND STREAMS API

COMP-202: Foundations of Programming. Lecture 7: Strings and Methods Jackie Cheung, Winter 2015

The for Loop. Lesson 11

Following is the general form of a typical decision making structure found in most of the programming languages:

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

1. Short circuit AND (&&) = if first condition is false then the second is never evaluated

Chapter 4 Defining Classes I

Primitive Data, Variables, and Expressions; Simple Conditional Execution

Full file at

Java Workshop Lambda Expressions

CS 106 Introduction to Computer Science I

Section 2.2 Your First Program in Java: Printing a Line of Text

( &% class MyClass { }

Time : 1 Hour Max Marks : 30

Please answer the following questions. Do not re-code the enclosed codes if you have already completed them.

Introduction to Typed Racket. The plan: Racket Crash Course Typed Racket and PL Racket Differences with the text Some PL Racket Examples

if (x == 0); System.out.println( x=0 ); if (x = 0) System.out.println( x=0 );

Closures. Mooly Sagiv. Michael Clarkson, Cornell CS 3110 Data Structures and Functional Programming

VENTURE. Section 1. Lexical Elements. 1.1 Identifiers. 1.2 Keywords. 1.3 Literals

Functions. Lab 4. Introduction: A function : is a collection of statements that are grouped together to perform an operation.

Mobile App:IT. Methods & Classes

Software Design and Analysis for Engineers

Class 1: Homework. Intro to Computer Science CSCI-UA.0101 New York University Courant Institute of Mathematical Sciences Fall 2017

Object Oriented Design

PIC 20A Anonymous classes, Lambda Expressions, and Functional Programming

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find

G52CPP C++ Programming Lecture 9

Lecture 05: Methods. AITI Nigeria Summer 2012 University of Lagos.

Lecture Notes for CS 150 Fall 2009; Version 0.5

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #43. Multidimensional Arrays

Index COPYRIGHTED MATERIAL

WEEK 4 OPERATORS, EXPRESSIONS AND STATEMENTS

Summer Assignment for the School Year

CS 106 Introduction to Computer Science I

CSE 413 Spring Introduction to Ruby. Credit: Dan Grossman, CSE341

Pace University. Fundamental Concepts of CS121 1

CONTENTS: What Is Programming? How a Computer Works Programming Languages Java Basics. COMP-202 Unit 1: Introduction

CIS October 16, 2018

1 Getting used to Python

Transcription:

LAMBDA EXPRESSIONS Summer 2018

LAMBDA EXPRESSIONS USES Introduced in Java SE 8, lambda expressions are a way to create single-method classes in your code in a much less cumbersome manner than anonymous classes/local classes Like with anonymous classes, these work best when you only need the method in one place One way to think about lambda expressions is as anonymous methods A great time to use for lambda expressions are functional interfaces interfaces with one method (e.g. many of the event listeners) An interface with static and default methods is still considered a functional interface if it only has one abstract method In addition to regular functional interfaces that perform specific functions, Java now includes a wide variety of general functional interfaces which are ideal for lambda expressions

STANDARD FUNCTIONAL INTERFACES Found in java.util.function a few examples Predicate<T> - contains a predicate function (boolean function) with one argument Function<T, R> - represents a function that accepts an argument of type T and produces a result of type R IntConsumer a function that accepts a single integer argument and returns no result LongSupplier a function that accepts no arguments and returns a long BinaryOperator<T> - a function that accepts two arguments of type T and produces a result of the same type BiFunction<T, U, R> - a function that accepts two arguments (of type T and U) and returns a result of type R

SYNTAX OF LAMBDA EXPRESSIONS The basic format of a lambda expression is: parameters -> body The parameters are a comma-separated list enclosed in parentheses. However, if there is only one parameter you can leave off the parentheses. You also do not have to specify the types of the parameters (sometimes it is necessary if the compiler cannot figure out the type) You can also have lambdas with no parameters So, you may have lambda expressions which look like the following: p -> body () -> body (a, b) -> body (Class c) -> body (stringvariable, array, intvar, othervar) -> body Between the parameters and the body you have the arrow token, which consists of a dash followed by the greater than sign: ->

SYNTAX OF LAMBDA EXPRESSIONS The body of a lambda expression contains either a single expression or statement block For a single expression that is not a return statement, you just place the expression to the right of the arrow token and the lambda expression evaluates the expression and returns its value (or, if it is a void expression, returns nothing) So, for example, this statement returns true if the String s is all lowercase and shorter than 200 characters: s -> s.equals(s.tolowercase()) && s.length() < 200 and this statement would return nothing, but would print out the String s s -> System.out.println(s) Notice that there is no semi-colon required when the lambda contains a single expression only

SYNTAX OF LAMBDA EXPRESSIONS If the body consists of a statement block rather than a single expression, you must enclose it in curly braces {}, just like any other statement block These can have return statements or not as determined by the situation So, the following is a valid lambda expression that takes 2 ints and returns an int: (x, y) -> { } System.out.println( x = + x); System.out.println( y = + y); z = x + y; System.out.println( z = + z); return z;

LAMBDAS VS ANONYMOUS CLASSES As you can see from the syntax, lambda expressions are functionally similar to an anonymous class In fact, every time you can use a lambda expression, you COULD use an anonymous class The main benefit of a lambda expression is the concise syntax, as you can leave a lot out that would be required for an anonymous class Parameter types, new operator, interface type, and method name are all found in every anonymous class but not lambda expressions There are some drawbacks to using a lambda expression, however Anonymous classes work with any class or interface (no matter how many methods), but lambda expressions can only have exactly one method Anonymous classes can contain member data, lambda expressions cannot Anonymous classes can have their own (non-inherited) methods, lambda expressions cannot

TARGET TYPING Lambda expressions are typed based on a combination of their parameters and return type, as well as what interface type the compiler is expected The type the compiler is expecting is called the target type This means that the same lambda expression could be used in multiple places, but have different types You can only use lambda expressions where the compiler can determine the target type: Variable declarations Assignments Return statements Array initializers Method arguments Lambda expression bodies Conditional expressions Casting expressions

TARGET TYPING, EXAMPLE As an example, suppose you have the following methods: public void dosomething1(list<integer> list, IntConsumer consumer) public void dosomething2(list<integer> list, Consumer<Integer> consumer) public void dosomething3(list<string> list, Consumer<String> consumer) Because the second parameter in all three methods consists of a functional interface that has a single method that takes some object and is of void return type, you can actually use the same lambda expression for all three parameters and because of target typing, they end up having different types. In this call, the second parameter is of type IntegerConsumer and the parameter x is an int: dosomething1(list, x -> System.out.println(x));

TARGET TYPING, EXAMPLE In this call, the second parameter is of type Consumer<Integer> and the parameter x is an Integer: dosomething2(list, x -> System.out.println(x)); In this call, the second parameter is of type Consumer<String> and the parameter x is a String: dosomething3(list, x -> System.out.println(x));

LOCAL VARIABLES/SCOPING Like local classes, a lambda expression can only access local variables and parameters of the block enclosing it that are final or effectively final However, unlike local classes, the lambda expression does not create a new level of scope. As an example, this will cause an error (a has already been declared): int a = 5; int b = 17; IntConsumer consumer = c -> { } int a = c; System.out.println(a);

LOCAL VARIABLES SCOPING This will also cause the same error: int a = 5; int b = 17; IntConsumer consumer = a -> { int d = a; System.out.println(d) }

EXAMPLES This example contains a few simple lambda expressions and a method that takes one as a parameter This example shows different predicates being passed into the PrintSome function These two files (test file is here, frame is here) show using Lambda expressions as event handlers in Swing.