A few of the more significant changes and additions. James Brucker

Slides:



Advertisements
Similar presentations
AP Computer Science Anthony Keen. Computer 101 What happens when you turn a computer on? –BIOS tries to start a system loader –A system loader tries to.
Advertisements

Intro to Scala Lists. Scala Lists are always immutable. This means that a list in Scala, once created, will remain the same.
INTERFACES IN JAVA 1.Java Does not support Multiple Inheritance directly. Multiple inheritance can be achieved in java by the use of interfaces. 2.We need.
1 SSD3 - Unit 2 Java toString & Equals Presentation Class Website:
Written by: Dr. JJ Shepherd
Lecture 18 Review the difference between abstract classes and interfaces The Cloneable interface Shallow and deep copies The ActionListener interface,
Chapter 17 Java SE 8 Lambdas and Streams
Appendix B: Lambda Expressions In the technical keynote address for JavaOne 2013, Mark Reinhold, chief architect for the Java Platform Group at Oracle,
Lambdas and Streams. Functional interfaces Functional interfaces are also known as single abstract method (SAM) interfaces. Package java.util.function.
1 CSC111H Graphical User Interfaces (GUIs) Introduction GUIs in Java Understanding Events A Simple Application The Containment Hierarchy Layout Managers.
Lambda Expressions In the technical keynote address for JavaOne 2013, Mark Reinhold, chief architect for the Java Platform Group at Oracle, described lambda.
Java8 Released: March 18, Lambda Expressions.
Written by: Dr. JJ Shepherd
JAVA 8 AND FUNCTIONAL PROGRAMMING. What is Functional Programming?  Focus on Mathematical function computations  Generally don’t think about “state”
Mid-Year Review. Coding Problems In general, solve the coding problems by doing it piece by piece. Makes it easier to think about Break parts of code.
Lambdas and Streams. Stream manipulation Class Employee represents an employee with a first name, last name, salary and department and provides methods.
Lecture 5:Interfaces and Abstract Classes Michael Hsu CSULA.
Functional Processing of Collections (Advanced) 6.0.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
3.1 Objects. Data type. Set of values and operations on those values. Primitive/Built-In types. n Usually single values n Can build arrays but they can.
April 13, 1998CS102-02Lecture 3-1 Data Types in Java CS Lecture 3-1 Java’s Central Casting.
Lambdas & Streams Laboratory
Lecture 5:Interfaces and Abstract Classes
Iterators.
CS314 – Section 5 Recitation 10
Modern Programming Tools And Techniques-I
EECE 310: Software Engineering
Taking Java from purely OOP by adding “functional level Programming”
ADT’s, Collections/Generics and Iterators
CHAPTER 7 & 8 REVIEW QUESTIONS
Recitation 11 Lambdas added to Java 8.
Methods Attributes Method Modifiers ‘static’
Lambdas ---anonymous functions---
Functional Processing of Collections (Advanced)
Java Algorithms.
Functional Programming with Java
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.
CS 302 Week 11 Jim Williams, PhD.
Designing with Interfaces
Topic 7 Interfaces I once attended a Java user group meeting where James Gosling (one of Java's creators) was the featured speaker. During the memorable.
Anonymous Classes A short-cut for defining classes when you want to create only one object of the class.
Polymorphism.
Generics and Type Parameters
Streams.
null, true, and false are also reserved.
CSC 113: Computer programming II
Conditional Statements
08/15/09 Design Patterns James Brucker.
CSE 1030: Implementing Non-Static Features
COS 260 DAY 10 Tony Gauvin.
Java Collections Framework
Collections James Brucker.
Functional interface.
Barb Ericson Georgia Institute of Technology Oct 2005
Effective Java, 3rd Edition Chapter 7: Lambdas and Streams
Interator and Iterable
Constructors, GUI’s(Using Swing) and ActionListner
Generics, Lambdas, Reflections
Computer Science 312 Lambdas in Java 1.
Computer Science 312 What’s New in Java 8? 1.
Lambda Expressions.
Suggested self-checks: Section 7.11 #1-11
Abstract Method & Abstract Classes
Chapter 11 Inheritance and Polymorphism Part 1
Java String Class String is a class
Review for Midterm 3.
„Lambda expressions, Optional”
Chengyu Sun California State University, Los Angeles
FINAL EXAM Final Exam Tuesday, May 3: 1:00 - 3:00 PM (Phys 112)
Generics, Lambdas and Reflection
Presentation transcript:

A few of the more significant changes and additions. James Brucker Java 8 New Features A few of the more significant changes and additions. James Brucker

Interfaces Default methods instance methods can have method code! use the qualifier default class "inherits" the default implementation Static methods with code Interfaces can have static methods, which must have code.

Default Method in Interfaces Add a getCurrency method to Valuable with default implementation. public interface Valuable { /** value of this item. This is abstract. */ public double getValue(); /** Get the currency. Default is "Baht". */ default public String getCurrency() { return "Baht"; } // ILLEGAL: Cannot override an existing method // default String toString() { return "error!": }

Static Method in Interface Add a getCurrency method to Valuable with default implementation. public interface Valuable { /** value of this item. This is abstract. */ public double getValue(); /** Create money (static). */ static Valuable create(double value) { return MoneyFactory.getInstance() .createMoney(value); }

Why add default methods? Java added new methods to existing interfaces. How to do that without breaking existing applications? Example: Iterable has a new "forEach" method: <<interface>> Iterable<T> iterator(): Iterator<T> forEach(c: Consumer<T>) ← New method

Iterable has a forEach() method The Iterable interface has a default forEach() method that invokes a Consumer object with each element of the Iterable. <<interface>> Iterable<T> iterator(): Iterator<T> forEach(c: Consumer<T>) <<interface>> Consumer<T> accept(arg: T): void A default method

Print a List of Students using loop The old way: List<Student> classlist = Registrar.getStudents("01219113"); // print each student using for-each loop for( Student s: classlist ) { System.out.println(s); }

Using forEach with a List New way: use forEach and a Consumer List<Student> classlist = Registrar.getStudents("01219113"); // print each student classlist.forEach( // Consumer as Anonymous Class new Consumer<Student>() { public void accept(Student s) { System.out.println(s); } } ); Let's make the code shorter using a Lambda expression...

Using forEach with Lambda Lambdas (anonymous functions) are another new Java 8 feature List<Student> list = Registrar.getStudents("01219113"); // print each student /* Consumer as Lambda Expression */ list.forEach( (s) -> System.out.println(s) ); Let's make this code even shorter using a Method Reference.

Method Reference for Lambda The Lambda just calls System.out.println(s) with the same parameter (s), so we can refer to "println" directly. List<Student> classlist = Registrar.getStudents("01219113"); // print each student /* Consumer as Method Reference */ classlist.forEach( System.out::println );

Lambda Expressions Lambdas are "anonymous functions". A Lambda implements an interface with one abstract method. // Runnable as anonymous class Runnable mytask = new Runnable() { public void run( ) { System.out.println("I'm running"); } }; // Runnable as Lambda Runnable mytask = () -> { System.out.println("I'm running"); };

How to Invoke a Lambda? Exactly the same as object defined using anonymous class. // Runnable mytask as Lambda Runnable mytask = () -> System.out.println("I'm running"); // Invoke the method: mytask.run();

Lambda Shortcuts If the method has only one statement, you may omit { }. // Runnable as Lambda Runnable mytask = () -> { System.out.println("I'm running"); }; // Lambda shortcut notation Runnable mytask = () -> System.out.println("I'm running");

Swing ActionListener An ActionListener that reads a text field. private JTextField inputField; ActionListener inputListener = new ActionListener( ) { public void actionPerformed(ActionEvent e){ String input = inputField.getText(); inputField.setText(""); processInput( input ); } }; inputField.addActionListener(inputListener);

ActionListener using Lambda Java can infer the parameter type (ActionEvent) private JTextField inputField; ActionListener inputListener = (event) -> { String input = inputField.getText(); inputField.setText(""); processInput( input ); }; inputField.addActionListener(inputListener);

Lambda that returns a value Compare strings by length Comparator<String> compByLength = // anonymous class new Comparator<String>() { public int compare(String a, String b) { return Integer.compare(a.length(), b.length()); } }; Integer.compare(int a, int b) is same as: Integer.valueOf(a).compareTo( Integer.valueOf(b) );

Lambda that returns a value Compare strings by length Comparator<String> compByLength = // Lambda express returning a value (a,b) -> Integer.compare(a.length(), b.length()); Java can infer from "Comparator<String>" that a and b are type String. So, we don't have to write it.

Streams All collections now support use of streams. New classes and interfaces are in package: java.util.stream Several new "functional interfaces" that are needed for streams: java.util.function

Simple Stream Examples Create a stream from a list: List<String> fruit = Arrays.asList("grape","orange", "banana", "apple", "durian", "pear", "guava"}; fruit.stream() // creates a stream of elements in fruit // what can you do with a Stream? A stream is like a pipeline. Each element of the stream is passed from one stream processor to the next.

Stream methods void forEach( Consumer ) Consumes each element of the stream. Stream filter( Predicate ) filter elements in the stream using a boolean test, called a Predicate Stream sorted( ) Stream sorted( Comparator ) sort elements in the Stream. This requires significant memory. Stream<R> map( Function<T,R> mapper ) Apply a function to map elements from one type (T) to another (R). T[ ] toArray( ) return elements as an array

<<interface>> Filter the fruit Write a test that returns true if string contains "a". Predicate<String> hasLetterA = new Predicate<String>() { public boolean test(String s) { return s.contains("a"); } }; <<interface>> Predicate<T> test(arg: T): boolean

<<interface>> Filter the fruit Write a Predicate that returns true if string contains "a". Predicate<String> hasLetterA = s -> s.contains("a"); fruit.stream().filter(hasLetterA).forEach( print ); <<interface>> Predicate<T> test(arg: T): boolean

References The Java Tutorial: https://docs.oracle.com/javase/tutorial Java 8 Features with Examples http://www.journaldev.com/2389/java-8-features-with- examples Has short examples of several features