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

Slides:



Advertisements
Similar presentations
Transparency No. 1 Java Collection API : Built-in Data Structures for Java.
Advertisements

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
CS220 Software Development Lecture: Multi-threading A. O’Riordan, 2009.
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.
Stacks. 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.
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:
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 List Stacks and Queues. Data Structures Data structure is a representation of data and the operations allowed on that data. Data structure is.
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.
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.
Recitation 4 Abstract classes, Interfaces. A Little More Geometry! Abstract Classes Shape x ____ y ____ Triangle area() base____ height ____ Circle area()
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
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.
1 Introduction  Algorithms  Data structures  Abstract data types  Programming with lists and sets © 2008 David A Watt, University of Glasgow Algorithms.
Dependency Injection Frameworks Technion – Institute of Technology Author: Assaf Israel - Technion 2013 ©
Java8 Released: March 18, Lambda Expressions.
Lecture 7 February 24, Javadoc version and author Tags These go in the comments before named classes. –Put your SS# on a separate line from the.
Iteration Abstraction SWE Software Construction Fall 2009.
M180: Data Structures & Algorithms in Java Stacks Arab Open University 1.
CSC 243 – Java Programming, Spring, 2014 Week 4, Interfaces, Derived Classes, and Abstract Classes.
Today… Preparation for doing Assignment 1. Invoking methods overview. Conditionals and Loops. Winter 2016CMPE212 - Prof. McLeod1.
Java 8 Lambda Expressions and You Technion – Institute of Technology Software Design (236700) Based on slides by: Sagie Davidovich, Assaf Israel Author:
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.
Monads Technion – Institute of Technology Software Design (236700) Author: Gal Lalouche - Technion 2016 © 1.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by.
Computer Science Victoria University of Wellington Copyright: david streader, Victoria University of Wellington Simple Design COMP
Lecture 6:Interfaces and Abstract Classes Michael Hsu CSULA.
Collections ABCD ABCD Head Node Tail Node array doubly linked list Traditional Arrays and linked list: Below is memory representation of traditional.
PySpark Tutorial - Learn to use Apache Spark with Python
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
Java Programming Language
Recitation 11 Lambdas added to Java 8.
Lambdas ---anonymous functions---
Java 9 New features 8/11/2017 Iason Dimitrios Rodis.
Functional Programming with Java
.NET and .NET Core 5.2 Type Operations Pan Wuming 2016.
Stacks.
Conditional Statements
Generic programming in Java
Iteration Abstraction
Functional interface.
Effective Java, 3rd Edition Chapter 7: Lambdas and Streams
Stacks.
Generics, Lambdas, Reflections
Computer Science 312 What’s New in Java 8? 1.
Lambda Expressions.
Interfaces.
Chengyu Sun California State University, Los Angeles
Threads and concurrency / Safety
Reasoning with Types.
Presentation transcript:

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

Life before Java 8 (cont.) Extracting employee names Extracting employee ages Author: Assaf Israel - Technion 2013 © 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: Assaf Israel - Technion 2013 © 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: Assaf Israel - Technion 2013 © 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(); } });

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)   Prior to Java 8, Java was the only programming languages in popular use without anonymous functions / blocks / lambdas / function pointers Author: Assaf Israel - Technion 2013 © 5

Enter Java 8! Extracting employee names Extracting employee ages Author: Assaf Israel - Technion 2013 © 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 ) Author: Assaf Israel - Technion 2013 © 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 talk about Scala  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 (e.g., in C# you can add extension methods to String ). Author: Assaf Israel - Technion 2013 © 8 List empNames = employees.stream().map(x -> x.getName()).collect(Collectors.toList());

Higher order functions  map is a high order function in stream  There are other similar higher order functions in stream  filter, map, flatmap, sorted, reduce… Author: Assaf Israel - Technion 2013 © 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  But what is returned if the list is empty?  Instead of working with null, a new type called 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: Assaf Israel - Technion 2013 © 10 employees.stream().noneMatch(x -> x.age < 18); Optional ageOfRichest = $.map(x -> x.getAge); Optional $ = employees.stream().max((x,y) -> x.salary – y.salary);

Higher order functions – Map-Reduce  Sum all salaries in the company  There are programming models that work on the MapReduce principle  e.g. Hadoop  collect is actually a form of mutable reduction  i.e., it reduces to a mutable container Author: Assaf Israel - Technion 2013 © 11 employees.stream().mapToInt(x -> x.getAge()) // note the mapToInt.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: Assaf Israel - Technion 2013 © 12 List topGrades = new ArrayList<>(); Collections.sort(students, new Comparator () { // sorts in place! 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); List topStudents = students.stream().filter(x -> x.getCountry() == "Israel").filter(x -> x.getGrade() > 90).sorted((x,y) -> x.getName().compareTo(y.getName())).collect(Collectors.toList());

Streams Author: Assaf Israel - Technion 2013 © 13  We only iterate over a stream once, even though we have 2 (or more) higher level functions  This is because streams are lazily evaluated  until we call collect, no iteration takes place  Streams also give us “free” parallelization 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  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  Lambdas are syntactic sugar for implementing Functional Interfaces Author: Assaf Israel - Technion 2013 © 14 List empNames = employees.stream().map(x -> x.getName()).collect(Collectors.toList()); interface Function { R apply(T t); // retracted default methods }

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: Assaf Israel - Technion 2013 © 15 new Thread(new Runnable() public void run() { System.out.println("Kill me :("); } }).start(); new Thread(() -> System.out.println("Woohoo! interface I { void A(); void B(); } // won’t compile

What else is new in Java 8?  New Date and Time APIs  Everything is now immutable  Support for unsigned arithmetic  Embedding JavaScript code in Java  Better integeration with JavaFX  A java library for developing rich client applications Author: Assaf Israel - Technion 2013 © 16 ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn"); engine.eval(“console.log('Hello World!');");