Effective Java, 3rd Edition Chapter 7: Lambdas and Streams

Slides:



Advertisements
Similar presentations
Object Oriented Programming with Java
Advertisements

Mutability SWE 332 Fall 2011 Paul Ammann. SWE 3322 Data Abstraction Operation Categories Creators Create objects of a data abstraction Producers Create.
Creating Classes from Other Classes Chapter 2 Slides by Steve Armstrong LeTourneau University Longview, TX  2007,  Prentice Hall.
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
Creating Classes from Other Classes Chapter 2. 2 Chapter Contents Composition Adapters Inheritance Invoking constructors from within constructors Private.
Java Interfaces Overview Java Interfaces: A Definition.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter N - 1 Chapter 13 Polymorphism is-a relationships Interfaces.
8.1 Classes & Inheritance Inheritance Objects are created to model ‘things’ Sometimes, ‘things’ may be different, but still have many attributes.
Java Classes Introduction and Chapter 1 Slides by Steve Armstrong LeTourneau University Longview, TX  2007,  Prentice Hall.
CS221 - Computer Science II Polymorphism 1 Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“ “Inheritance is.
1 Identifiers  Identifiers are the words a programmer uses in a program  An identifier can be made up of letters, digits, the underscore character (
1 Object-Oriented Software Engineering CS Interfaces Interfaces are contracts Contracts between software groups Defines how software interacts with.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Polymorphism, Inheritance Pt. 1 COMP 401, Fall 2014 Lecture 7 9/9/2014.
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.
Effective Java: Generics Last Updated: Spring 2009.
2000 Jordan Anastasiade. All rights reserved. 1 Class In this lesson you will be learning about: Class. Inheritance. Polymorphism. Nested and.
The Java Programming Language
AP Computer Science A – Healdsburg High School 1 Interfaces, Abstract Classes and the DanceStudio - Similarities and Differences between Abstact Classes.
Methods in Java. Program Modules in Java  Java programs are written by combining new methods and classes with predefined methods in the Java Application.
INTERFACES More OO Concepts. Interface Topics Using an interface Interface details –syntax –restrictions Create your own interface Remember polymorphism.
1 CSC/ECE 517 Fall 2010 Lec. 3 Overview of Eclipse Lectures Lecture 2 “Lecture 0” Lecture 3 1.Overview 2.Installing and Running 3.Building and Running.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Chapter 7: Class Inheritance F Superclasses and Subclasses F Keywords: super and this F Overriding methods F The Object Class F Modifiers: protected, final.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Java Classes Chapter 1. 2 Chapter Contents Objects and Classes Using Methods in a Java Class References and Aliases Arguments and Parameters Defining.
1 Interface &Implements. 2 An interface is a classlike construct that contains only constants variables and abstract methods definition. An interface.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Java Classes Introduction. Contents Introduction Objects and Classes Using the Methods in a Java Class – References and Aliases Defining a Java Class.
© 2011 Pearson Education, publishing as Addison-Wesley Chapter 1: Computer Systems Presentation slides for Java Software Solutions for AP* Computer Science.
Lecture 5:Interfaces and Abstract Classes Michael Hsu CSULA.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Lecture 6:Interfaces and Abstract Classes Michael Hsu CSULA.
Lecture 5:Interfaces and Abstract Classes
Modern Programming Tools And Techniques-I
Chapter 15 Abstract Classes and Interfaces
Software Development Java Classes and Methods
Inheritance and Polymorphism
Lecture 6: Composition and Inheritance
Recitation 11 Lambdas added to Java 8.
University of Central Florida COP 3330 Object Oriented Programming
Lambdas ---anonymous functions---
Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“ “Inheritance is new code that reuses old code. Polymorphism.
C++ -> Java - A High School Teacher's Perspective
Functional Programming with Java
EE 422C Java Reflection re·flec·tion rəˈflekSH(ə)n/ noun
Effective Java, Third Ed. Keepin’ it effective
Inheritance, Polymorphism, and Interfaces. Oh My
null, true, and false are also reserved.
Java Programming Language
Interfaces.
Abstract Class As per dictionary, abstraction is the quality of dealing with ideas rather than events. For example, when you consider the case of ,
Lecture 16 - Interfaces Professor Adams.
Generic programming in Java
Chapter 6 Array-Based Lists.
Java Inheritance.
A few of the more significant changes and additions. James Brucker
Computer Science 312 Lambdas in Java 1.
Computer Science 312 What’s New in Java 8? 1.
Chapter 14 Abstract Classes and Interfaces
Chap 2. Identifiers, Keywords, and Types
Winter 2019 CMPE212 5/25/2019 CMPE212 – Reminders
Chapter 11 Inheritance and Encapsulation and Polymorphism
Review for Midterm 3.
„Lambda expressions, Optional”
Java’s Stream API.
Chengyu Sun California State University, Los Angeles
Presentation transcript:

Effective Java, 3rd Edition Chapter 7: Lambdas and Streams Items 42-48 Last modified Fall 2018 Paul Ammann

More Item 42: Prefer lambdas to anonymous classes Old Java: interfaces with one method represented function types: // Anonymous class instance as function object - obsolete! Collections.sort(words, new Comparator<String>() { public int compare(String s1, String s2) { return Integer.compare(s1.length(), s2.length()); } }); In Java 8, use lambdas to instantiate small function objects: // Lambda expression as function object (replaces anonymous class) Collections.sort(words, (s1, s2) -> Integer.compare(s1.length(), s2.length())); With Comparator construction method: Collections.sort(words, comparingInt(String::length)); With new sort method added to List interface: words.sort(comparingInt(String::length));

More Item 42 A more complex enum example: old version // Enum type with constant-specific class bodies & data (Item 34) public enum Operation { PLUS("+") { public double apply(double x, double y) { return x + y; } }, MINUS("-") { public double apply(double x, double y) { return x - y; } }, TIMES("*") { public double apply(double x, double y) { return x * y; } }, DIVIDE("/") { public double apply(double x, double y) { return x / y; } }; private final String symbol; Operation(String symbol) { this.symbol = symbol; } @Override public String toString() { return symbol; } public abstract double apply(double x, double y); }

More Item 42 A more complex enum example: updated version // Enum with function object fields & constant-specific behavior public enum Operation { PLUS ("+", (x, y) -> x + y), MINUS ("-", (x, y) -> x - y), TIMES ("*", (x, y) -> x * y), DIVIDE("/", (x, y) -> x / y); private final String symbol; private final DoubleBinaryOperator op; // lambda instance field! Operation(String symbol, DoubleBinaryOperator op) { this.symbol = symbol; this.op = op; } @Override public String toString() { return symbol; } public double apply(double x, double y) { return op.applyAsDouble(x, y);

More Item 42 Anonymous classes still have their uses Downside for lambdas in constant-specific method bodies? They lack names and documentation, so keep them short! Sometimes a constant-specific method body is more readable Anonymous classes still have their uses Instantiating abstract classes Instantiating interfaces with multiple methods lambdas can’t references themselves

Item 43: Prefer method references to lambdas Where method references are shorter and clearer, use them; where they aren’t, stick with lambdas map.merge(key, 1, (count, incr) -> count + incr) vs. map.merge(key, 1, Integer::sum) Note that the merge() method in Map has the following documentation. What does that tell us about the example? default V merge(K key, V value, BiFunction<? super V,? super V,? extends V> remappingFunction) If the specified key is not already associated with a value or is associated with null, associates it with the given non-null value.

More Item 43 Java’s 5 kinds of method references Method Ref Type Example Lambda Equivalent Static Integer::parseInt str -> Integer.parseInt(str) Bound Instant.now()::isAfter Instant then = Instant.now(); t -> then.isAfter(t) Unbound String::toLowerCase str -> str.toLowerCase() Class Constructor TreeMap<K,V>::new () -> new TreeMap<K,V> Array Constructor int[]::new len -> new int[len]

Item 44: Favor the use of standard functional interfaces java.util.function has 43 predefined functional interfaces Use them! Usually better not to rewrite, but there are exceptions.

More Item 44 Java’s standard functional interfaces: variants on the 6 types below Interface Function Signature Example UnaryOperator<T> T apply(T t) String::toLowerCase BinaryOperator<T> T apply(T t1, T t2) BigInteger::add Predicate<T> boolean test(T t) Collection::isEmpty Function<T,R> R apply(T t) Arrays::asList Supplier<T> T get() Instant::now Consumer<T> void accept(T t) System.out::println

Item 45: Use streams judiciously Stuff

Item 46: Prefer side-effect-free functions in streams Stuff

Item 47: Prefer Collection to Stream as a return type Stuff

Item 48: Use caution when making streams parallel Stuff