Java 8 Lambda Expressions and You Technion – Institute of Technology Software Design (236700) Based on slides by: Sagie Davidovich, Assaf Israel Author:

Slides:



Advertisements
Similar presentations
Java 8 Technion – Institute of Technology Software Design (236700) Based on slides by: Sagie Davidovich, Assaf Israel Author: Assaf Israel - Technion 2013.
Advertisements

Generic programming in Java
CSE341: Programming Languages Lecture 11 Closures-ish Java & C Dan Grossman Fall 2011.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Road Map Introduction to object oriented programming. Classes
Interfaces. In this class, we will cover: What an interface is Why you would use an interface Creating an interface Using an interface Cloning an object.
Stacks. 2 What is a stack? A stack is a Last In, First Out (LIFO) data structure Anything added to the stack goes on the “top” of the stack Anything removed.
Recommendation: Play the game and attempt to answer the questions yourself without looking at the answers. You’ll learn much less if you just look at the.
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
Stacks (Revised and expanded from CIT 591). What is a stack? A stack is a Last In, First Out (LIFO) data structure Anything added to the stack goes on.
Stacks. 2 What is a stack? A stack is a Last In, First Out (LIFO) data structure Anything added to the stack goes on the “top” of the stack Anything removed.
Programming in Scala Chapter 1. Scala: both object-oriented and functional Scala blends –object-oriented and –functional programming in a –statically.
Generic Subroutines and Exceptions CS351 – Programming Paradigms.
Java CourseWinter 2009/10. Introduction Object oriented, imperative programming language. Developed: Inspired by C++ programming language.
Week 4-5 Java Programming. Loops What is a loop? Loop is code that repeats itself a certain number of times There are two types of loops: For loop Used.
CSE 331 Software Design & Implementation Hal Perkins Autumn 2012 Java Classes, Interfaces, and Types 1.
Monads Technion – Institute of Technology Software Design (236700) Author: Gal Lalouche - Technion 2015 © 1.
Java 8 Lambda expressions and you Technion – Institute of Technology Software Design (236700) Based on slides by: Sagie Davidovich, Assaf Israel Author:
CS2110: SW Development Methods Textbook readings: MSD, Chapter 8 (Sect. 8.1 and 8.2) But we won’t implement our own, so study the section on Java’s Map.
1 Review of Java Higher Level Language Concepts –Names and Reserved Words –Expressions and Precedence of Operators –Flow of Control – Selection –Flow of.
Chapter 3 Introduction to Collections – Stacks Modified
1 Abstraction  Identify important aspects and ignore the details  Permeates software development programming languages are abstractions built on hardware.
Scala Technion – Institute of Technology Software Design (236700) Based on slides by: Sagie Davidovich, Assaf Israel Author: Gal Lalouche - Technion 2015.
Polymorphism, Inheritance Pt. 1 COMP 401, Fall 2014 Lecture 7 9/9/2014.
Introduction to Java Prepared by: Ahmed Hefny. Outline Classes Access Levels Member Initialization Inheritance and Polymorphism Interfaces Inner Classes.
Putting it all together: LINQ as an Example. The Problem: SQL in Code Programs often connect to database servers. Database servers only “speak” SQL. Programs.
Functional Programming in Scheme and Lisp. Overview In a functional programming language, functions are first class objects. You can create them, put.
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
Dependency Injection Technion – Institute of Technology Author: Gal Lalouche - Technion 2015 ©
Best Practices. Contents Bad Practices Good Practices.
Comp 249 Programming Methodology Chapter 13 Interfaces & Inner Classes Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
1 final (the keyword, not the exam). 2 Motivation Suppose we’ve defined an Employee class, and we don’t want someone to come along and muck it up  E.g.,
Object Oriented Software Development
Java Basics Opening Discussion zWhat did we talk about last class? zWhat are the basic constructs in the programming languages you are familiar.
CS162 Week 1 Kyle Dewey. Overview Basic Introduction CS Accounts Scala survival guide.
Polymorphism Liskov 8. Outline equals() Revisiting Liskov’s mutable vs. not rule Polymorphism Uniform methods for different types “easy” polymorphism.
Dependency Injection Frameworks Technion – Institute of Technology Author: Assaf Israel - Technion 2013 ©
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Functional Programming IN NON-FUNCTIONAL LANGUAGES.
CS2102: Lecture on Abstract Classes and Inheritance Kathi Fisler.
Iteration Abstraction SWE Software Construction Fall 2009.
CSC 243 – Java Programming, Spring, 2014 Week 4, Interfaces, Derived Classes, and Abstract Classes.
Dependency Injection with Guice Technion – Institute of Technology Author: Gal Lalouche - Technion 2016 ©
Today… Preparation for doing Assignment 1. Invoking methods overview. Conditionals and Loops. Winter 2016CMPE212 - Prof. McLeod1.
12-CRS-0106 REVISED 8 FEB 2013 CSG2H3 Object Oriented Programming.
Monads Technion – Institute of Technology Software Design (236700) Author: Gal Lalouche - Technion 2016 © 1.
Lecture 6:Interfaces and Abstract Classes Michael Hsu CSULA.
Lecture 5:Interfaces and Abstract Classes
Java 8, Lambda Expressions and You
CS239-Lecture 4 FlumeJava Madan Musuvathi Visiting Professor, UCLA
EECE 310: Software Engineering
Generics, Lambdas, Reflections
Student Book An Introduction
Java 9 New features 8/11/2017 Iason Dimitrios Rodis.
Monads Author: Gal Lalouche - Technion 2017 © 1 1.
Functional Programming with Java
.NET and .NET Core 5.2 Type Operations Pan Wuming 2016.
Conditional Statements
Generic programming in Java
Iteration Abstraction
Spark and Scala.
Functional interface.
Effective Java, 3rd Edition Chapter 7: Lambdas and Streams
Stacks.
Generics, Lambdas, Reflections
Interfaces.
Java Statements B.Ramamurthy CS114A, CS504 4/23/2019 BR.
CMPE212 – Reminders Assignment 2 due next Friday.
„Lambda expressions, Optional”
Reasoning with Types.
Presentation transcript:

Java 8 Lambda Expressions and You Technion – Institute of Technology Software Design (236700) Based on slides by: Sagie Davidovich, Assaf Israel Author: Gal Lalouche - Technion 2016 © 1

Life before Java 8 (cont.) Extracting employee names Extracting employee ages Author: Gal Lalouche - Technion 2016© 2 public List empNames(List employees) { List result = new ArrayList<>(); for (Employee emp: employees) { result.add(emp.getName()); } return result; } public List empAges(List employees) { List result = new ArrayList<>(); for (Employee emp: employees) { result.add(emp.getAge()); } return result; } DuplicationVariation

Life before Java 8 (cont.) Lets identify the control structure, and extract the behavior into an object Author: Gal Lalouche - Technion 2016© 3 public List empNames(List employees){ List result = new ArrayList<>(); for (Employee emp: employees) { result.add(emp.getName()); } return result; } public interface Mapper { public T map(U u); } public List map(List aList, Mapper mapper) { List result = new ArrayList<>(); for (U u: aList) { result.add(mapper.map(u)); } return result; }

Life before Java 8 (cont.) Extracting employee names Extracting employee ages Author: Gal Lalouche - Technion 2016© 4 List empNames = map(employees, new Mapper () { public String map(Employee e) { e.getName(); } }); List empAges = map(employees, new Mapper () { public Integer map(Employee e) { e.getAge(); } }); Redundant

In the Kingdom of Nouns We removed the code duplication, but this is still very verbose…  Semantically, map is a higher level function  This means that it accepts a function as an argument (or returns a function)  Syntactically, functions do not exist as first class entities  All verbs (functions) have be accompanied by a noun (class)  /03/execution-in-kingdom-of-nouns.html /03/execution-in-kingdom-of-nouns.html  Prior to Java 8, Java was the only programming language in popular use without anonymous functions / blocks / lambdas / function pointers  This is not purely a syntactic issue; Java also lacked proper support for such function in its collections and standard libraries  Some libraries, like Guava, attempted to fill the voidGuava Author: Gal Lalouche - Technion 2016© 5

Enter Java 8! Extracting employee names Extracting employee ages Author: Gal Lalouche - Technion 2016© 6 List empNames = employees.stream().map(x -> x.getName()).collect(Collectors.toList()); List empAge = employees.stream().map(x -> x.getAge()).collect(Collectors.toList());

Let’s take a deeper look…  stream() is a default method of List  map is a higher level function of Stream  x -> x.getName() is a lambda expression  collect turns the Stream back to a normal Collection (in our case, a List )  But what does each of these terms mean? Author: Gal Lalouche - Technion 2016© 7 List empNames = employees.stream().map(x -> x.getName()).collect(Collectors.toList());

default Methods  default methods are default implementations for interfaces  This way you can add new functionality to an existing interface without breaking all depending code  In our case, we added the stream() method to Collection  So is this the same as multiple inheritance ?  Not exactly, the behavior more closely resembles Traits, which we will discuss in detail when we talk about Scala  For now, suffice to say that since there is neither conflict resolution nor constructors, the model is much simpler  So are these extension methods (a la C#)?  No, because extension methods are actually syntactic sugar for static decorators  You can’t add methods yourself to existing classes (e.g., in C# you can add extension methods to String ). Author: Gal Lalouche - Technion 2016© 8 List empNames = employees.stream().map(x -> x.getName()).collect(Collectors.toList());

Higher order functions  map is a higher order function in stream  That is, a function that takes a function  There are other similar higher order functions in stream  filter, map, flatMap, sorted, reduce…  Similar solution exist in other languages  LINQ in C#, itertools in Python, Enumerable in Ruby, etc. Author: Gal Lalouche - Technion 2016© 9 List empNames = employees.stream().map(x -> x.getName()).collect(Collectors.toList());

Higher order functions – API examples  Assure we are not hiring anyone underage  Find the highest paid individual in the company  What is returned if the list is empty?  Instead of working with null, a new type Optional is returned  Optional can be present (i.e. not null ) or not (i.e. null )  Has a method get() that returns T or throws an exception  Optional itself has higher order functions Author: Gal Lalouche - Technion 2016© 10 assert employees.stream().noneMatch(x -> x.age < 18); Optional ageOfRichest = $.map(x -> x.getAge); Optional is actually something called a Monad We will discuss monads next week Optional $ = employees.stream().max((x,y) -> x.salary – y.salary); What’s this?

Higher order functions – Map-Reduce  Sum of all salaries in the company  There are programming models that work on the MapReduce principle  e.g. Hadoop Author: Gal Lalouche - Technion 2016© 11 employees.stream().mapToInt(Employee::getSalary)// note the mapToInt... why?.reduce(0, Integer::sum) // could also be done with Lambdas, or simply.sum()

Higher Order function – A more complex example  Get Israeli students with a top grade sorted by name (in Java 7)  In Java 8: Author: Gal Lalouche - Technion 2016© 12 List topGrades = new ArrayList<>(); Collections.sort(students, new Comparator () { public int compare(Student student1, Student student2) { return student1.getName().compareTo(student2.getName()); } }); for (Student student: students) if (student.getCountry() == "Israel") if (student.getGrade() >= 90) topGrades.add(student); Sorts in place! Why is this bad? Depth of 3! List topStudents = students.stream().filter(x -> x.getCountry() == "Israel").filter(x -> x.getGrade() > 90).sorted((x, y) -> y.getGrade() - x.getGrade()).collect(Collectors.toList());

Streams Author: Gal Lalouche - Technion 2016© 13  We only iterate over a stream once, even if we have two (or more) higher level functions  This is because streams are lazily evaluated  until we call collect, no iteration takes place  collect is actually a form of mutable reduction  i.e., it reduces to a mutable container  They also provide us with a uniform API  Streams also give us “free” parallelization (why is it so easy?) List topStudents = students.stream().parallel().filter(x -> x.getCountry() == "Israel").filter(x -> x.getGrade() > 90).sorted((x, y) -> y.getGrade() - x.getGrade()).collect(Collectors.toList());

Lambdas and Default Methods  The signature for map is: map(Function mapper)  And here is the signature for Function:  An interface which has single abstract (i.e., non- default ) method can be called a Functional Interface  So is Java now a functional language?  Nope  Lambdas are just syntactic sugar for implementing Functional Interfaces  Functions aren’t first-class citizens, since functions aren’t even a proper part of the Java language, just a standard library interface Author: Gal Lalouche - Technion 2016© 14 List empNames = employees.stream().map(x -> x.getName()).collect(Collectors.toList()); interface Function { R apply(T t); // default methods retracted }

Lambdas (cont.) We can also use lambda with “old” API!  Old code  New code  We can use the annotation to tell the compiler that the interface should be functional (a ) Author: Gal Lalouche - Technion 2016© 15 new Thread(new Runnable() public void run() { System.out.println("Kill me :["); } }).start(); new Thread(() -> System.out.println("PARTEH! :D|-< :D/-< interface I { void A(); void B(); } // won’t compile

What else is new in Java 8?  New Date and Time APIs New Date and Time APIs  Everything is now immutable, and immutable is good  Support for unsigned arithmetic (no uint type) Support for unsigned arithmetic  Embedding JavaScript code in Java Embedding JavaScript code in Java  Better integration with JavaFX  Java library for developing rich client applications  Alternative to swing, which is no longer in active development Author: Gal Lalouche - Technion 2016© 16 ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn"); engine.eval("console.log('Hello World!');");