Overview of Java 8 Functional InterfacesDouglas C. edu/ schmidtProfessor of Computer ScienceInstitute for SoftwareIntegrated SystemsVanderbilt UniversityNashville, Tennessee, USA
Learning Objectives in this Lesson Recognize foundational functionalprogramming features in Java 8, e.g., Lambda expressions Method & constructor references Key functional erfacesSupplier2Consumer
Learning Objectives in this Lesson Recognize foundational functionalprogramming features in Java 8, e.g., Lambda expressions Method & constructor references Key functional interfaces3 8’s concurrency/parallelism frameworksThese features are the foundation for Java
Learning Objectives in this Lesson Recognize foundational functionalprogramming features in Java 8 Understand how these Java 8 featuresare applied in concise example programs4See ster/Java8
Overview of CommonFunctional Interfaces5
Overview of Common Functional Interfaces A functional interface contains only one abstract method6See ces
Overview of Common Functional Interfaces A functional interface is the type used for a parameter when a lambdaexpression or method reference is passed as an argument T void runTest(Function T, T fact, T n) {long startTime System.nanoTime();T result fact.apply(n));long stopTime (System.nanoTime() - startTime) / 1 000 000;.}runTest(ParallelStreamFactorial::factorial, n);runTest(SequentialStreamFactorial::factorial, n);.7See ster/Java8/ex16
Overview of Common Functional Interfaces A functional interface is the type used for a parameter when a lambdaexpression or method reference is passed as an argument T void runTest(Function T, T fact, T n) {long startTime System.nanoTime();T result fact.apply(n));long stopTime (System.nanoTime() - startTime) / 1 000 000;.}runTest(ParallelStreamFactorial::factorial, n);.static BigInteger factorial(BigInteger n) {return LongStream.rangeClosed(1, (BigInteger.ONE, BigInteger::multiply);}8
Overview of Common Functional Interfaces Java 8 defines many types offunctional interfaces9See on/package-summary.html
Overview of Common Functional Interfaces Java 8 defines many types offunctional interfaces This list is large due to theneed to support referencetypes & primitive types.10See dzone.com/articles/whats-wrong-java-8-part-ii
Overview of Common Functional Interfaces Java 8 defines many types offunctional interfaces This list is large due to theneed to support referencetypes & primitive cesWe focus on the most commontypes of functional interfacesSupplier11Consumer
Overview of Common Functional Interfaces Java 8 defines many types offunctional interfaces This list is large due to theneed to support referencetypes & primitive cesSupplierConsumer12 upcoming examples are “stateless”!All usages of functional interfaces in the
Overview of FunctionalInterfaces: Predicate13
Overview of Common Functional Interfaces: Predicate A Predicate performs a test that returns true or false, e.g., public interface Predicate T { boolean test(T t); }14See on/Predicate.html
Overview of Common Functional Interfaces: Predicate A Predicate performs a test that returns true or false, e.g., public interface Predicate T { boolean test(T t); }15See on/Predicate.html
Overview of Common Functional Interfaces: Predicate A Predicate performs a test that returns true or false, e.g., public interface Predicate T { boolean test(T t); }Map String, Integer iqMap new ConcurrentHashMap String, Integer () { {put("Larry", 100); put("Curly", 90); put("Moe", 110);}};Create a map of “stooges” & their oveIf(entry - entry.getValue() 100);System.out.println(iqMap);16See ster/Java8/ex10
Overview of Common Functional Interfaces: Predicate A Predicate performs a test that returns true or false, e.g., public interface Predicate T { boolean test(T t); }Map String, Integer iqMap new ConcurrentHashMap String, Integer () { {put("Larry", 100); put("Curly", 90); put("Moe", 110);}};System.out.println(iqMap);This predicate lambda deletesentries with iq 100iqMap.entrySet().removeIf(entry - entry.getValue() 100);System.out.println(iqMap);17See tion.html#removeIf
Overview of Common Functional Interfaces: Predicate A Predicate performs a test that returns true or false, e.g., public interface Predicate T { boolean test(T t); }Map String, Integer iqMap new ConcurrentHashMap String, Integer () { {put("Larry", 100); put("Curly", 90); put("Moe", 110);}entry is short for (EntrySet String,};System.out.println(iqMap);Integer entry), which leverages the Java8 compiler’s type inference capabilitiesiqMap.entrySet().removeIf(entry - entry.getValue() 100);System.out.println(iqMap);18See ypeInference.html
Overview of Common Functional Interfaces: Predicate A Predicate performs a test that returns true or false, e.g., public interface Predicate T { boolean test(T t); }interface Collection E {.default boolean removeIf(Predicate ? super E filter) {.final Iterator E each iterator();while (each.hasNext()) {if (filter.test(each.next())) {each.remove();.19 uses the predicate passed to itHere’s how the removeIf() method
Overview of Common Functional Interfaces: Predicate A Predicate performs a test that returns true or false, e.g., public interface Predicate T { boolean test(T t); }interface Collection E {.default boolean removeIf(Predicate ? super E filter) {.final Iterator E each iterator();entry - while (each.hasNext()) {entry.getValue()if (filter.test(each.next())) { 100each.remove();.20the lambda expression passed to itThis predicate parameter is bound to
Overview of Common Functional Interfaces: Predicate A Predicate performs a test that returns true or false, e.g., public interface Predicate T { boolean test(T t); }interface Collection E {.default boolean removeIf(Predicate ? super E filter) {.final Iterator E each iterator();entry - while (each.hasNext()) {entry.getValue()if (filter.test(each.next())) { 100each.remove();.if (each.next().getValue() 100)The ‘entry’ in the lambda predicate 21is replaced by the parameter to test()
Overview of FunctionalInterfaces: Function22
Overview of Common Functional Interfaces: Function A Function applies a computation on 1 parameter & returns a result, e.g., public interface Function T, R { R apply(T t); }23See on/Function.html
Overview of Common Functional Interfaces: Function A Function applies a computation on 1 parameter & returns a result, e.g., public interface Function T, R { R apply(T t); }24See on/Function.html
Overview of Common Functional Interfaces: Function A Function applies a computation on 1 parameter & returns a result, e.g., public interface Function T, R { R apply(T t); }Map Integer, Integer primeCache new ConcurrentHashMap ();This map caches the resultsof prime # computations.Long smallestFactor primeCache.computeIfAbsent(primeCandidate, (key) - primeChecker(key));.Integer primeChecker(Integer primeCandidate) {. // Returns 0 if a number if prime or the smallest// factor if it’s not prime}25See ster/Java8/ex9
Overview of Common Functional Interfaces: Function A Function applies a computation on 1 parameter & returns a result, e.g., public interface Function T, R { R apply(T t); }Map Integer, Integer primeCache new ConcurrentHashMap ();If key isn’t already associated with avalue, compute the value using the givenmapping function & enter it into the map.Long smallestFactor primeCache.computeIfAbsent(primeCandidate, (key) - primeChecker(key));.Integer primeChecker(Integer primeCandidate) {. // Returns 0 if a number if prime or the smallest// factor if it’s not prime}See rent/ConcurrentHashMap.html#computeIfAbsent26
Overview of Common Functional Interfaces: Function A Function applies a computation on 1 parameter & returns a result, e.g., public interface Function T, R { R apply(T t); }Map Integer, Integer primeCache new ConcurrentHashMap ();This method provides atomic“check then act” semantics.Long smallestFactor primeCache.computeIfAbsent(primeCandidate, (key) - primeChecker(key));.Integer primeChecker(Integer primeCandidate) {. // Returns 0 if a number if prime or the smallest// factor if it’s not prime}27See dig.cs.illinois.edu/papers/checkThenAct.pdf
Overview of Common Functional Interfaces: Function A Function applies a computation on 1 parameter & returns a result, e.g., public interface Function T, R { R apply(T t); }Map Integer, Integer primeCache new ConcurrentHashMap ();A lambda expression that calls a function.Long smallestFactor primeCache.computeIfAbsent(primeCandidate, (key) - primeChecker(key));.Integer primeChecker(Integer primeCandidate) {. // Returns 0 if a number if prime or the smallest// factor if it’s not prime}28
Overview of Common Functional Interfaces: Function A Function applies a computation on 1 parameter & returns a result, e.g., public interface Function T, R { R apply(T t); }Map Integer, Integer primeCache new ConcurrentHashMap ();Could also be a passed as a method reference.Long smallestFactor primeCache.computeIfAbsent(primeCandidate, this::primeChecker);.Integer primeChecker(Integer primeCandidate) {. // Returns 0 if a number if prime or the smallest// factor if it’s not prime}29
Overview of Common Functional Interfaces: Function A Function applies a computation on 1 parameter & returns a result, e.g., public interface Function T, R { R apply(T t); }class ConcurrentHashMap K,V .public V computeIfAbsent(K key,Function ? super K, ? extends V mappingFunction) {.if ((f tabAt(tab, i (n - 1) & h)) null).if ((val mappingFunction.apply(key)) ! null)node new Node K,V (h, key, val, null);.30Here’s how the computeIfAbsent() methoduses the function passed to it
Overview of Common Functional Interfaces: Function A Function applies a computation on 1 parameter & returns a result, e.g., public interface Function T, R { R apply(T t); }class ConcurrentHashMap K,V .this::primeCheckerpublic V computeIfAbsent(K key,Function ? super K, ? extends V mappingFunction) {.if ((f tabAt(tab, i (n - 1) & h)) null).if ((val mappingFunction.apply(key)) ! null)node new Node K,V (h, key, val, null);.The function parameter is bound to 31this::primeChecker method reference
Overview of Common Functional Interfaces: Function A Function applies a computation on 1 parameter & returns a result, e.g., public interface Function T, R { R apply(T t); }class ConcurrentHashMap K,V .public V computeIfAbsent(K key,Function ? super K, ? extends V mappingFunction) {.if ((f tabAt(tab, i (n - 1) & h)) null).if ((val mappingFunction.apply(key)) ! null)node new Node K,V (h, key, val, null);.if ((val primeChecker(key)) ! null)The apply() method is replaced with32the primeChecker() lambda function
Overview of Common Functional Interfaces: Function This example also shows a Function, e.g., public interface Function T, R { R apply(T t); }List Thread threads new ArrayList (Arrays.asList(new Thread("Larry"),new Thread("Curly"),new Thread("Moe")));Create a list of threads namedafter the three ads.forEach(System.out::println);33See ster/Java8/ex5
Overview of Common Functional Interfaces: Function This example also shows a Function, e.g., public interface Function T, R { R apply(T t); }List Thread threads new ArrayList (Arrays.asList(new Thread("Larry"),new Thread("Curly"),new Thread("Moe")));A method reference to a Function used to sort threads by .forEach(System.out::println);34See -list
Overview of Common Functional Interfaces: Function This example also shows a Function, e.g., public interface Function T, R { R apply(T t); }List Thread threads new ArrayList (Arrays.asList(new Thread("Larry"),new Thread("Curly"),new Thread("Moe")));This method uses the Thread::getName method referenceto impose a total ordering on some collection of ads.forEach(System.out::println);35See ator.html#comparing
Overview of Common Functional Interfaces: Function This example also shows a Function, e.g., public interface Function T, R { R apply(T t); }interface Comparator {.static T, U extends Comparable ? super U Comparator T comparing(Function ? super T, ? extends U keyEx) {return ((c1, c2) - keyEx.apply(c1).compareTo(keyEx.apply(c2)); }36 uses the function passed to itHere’s how the comparing() method
Overview of Common Functional Interfaces: Function This example also shows a Function, e.g., public interface Function T, R { R apply(T t); }interface Comparator {.static T, U extends Comparable ? super U Comparator T comparing(Function ? super T, ? extends U keyEx) {return ((c1, c2) - keyEx.apply(c1).compareTo(keyEx.apply(c2)); }The comparing() method is passeda Function parameter called keyEx37
Overview of Common Functional Interfaces: Function This example also shows a Function, e.g., public interface Function T, R { R apply(T t); }interface Comparator {.static T, U extends Comparable ? super U Comparator T comparing(Function ? super T, ? extends U keyEx) {return ((c1, c2) - ly(c2)); }38 is bound to the keyEx parameterThe Thread::getName method reference
Overview of Common Functional Interfaces: Function This example also shows a Function, e.g., public interface Function T, R { R apply(T t); }interface Comparator {.static T, U extends Comparable ? super U Comparator T comparing(Function ? super T, ? extends U keyEx) {return ((c1, c2) - keyEx.apply(c1).compareTo(keyEx.apply(c2)); }c1 & c2 are the stringsbeing compared by sort()39
Overview of Common Functional Interfaces: Function This example also shows a Function, e.g., public interface Function T, R { R apply(T t); }interface Comparator {.static T, U extends Comparable ? super U Comparator T comparing(Function ? super T, ? extends U keyEx) {return ((c1, c2) - keyEx.apply(c1).compareTo(keyEx.apply(c2)); }The apply() method of the keyExfunction is used to compare strings40
Overview of Common Functional Interfaces: Function This example also shows a Function, e.g., public interface Function T, R { R apply(T t); }interface Comparator {.static T, U extends Comparable ? super U Comparator T comparing(Function ? super T, ? extends U keyEx) {return ((c1, c2) - keyEx.apply(c1).compareTo(keyEx.apply(c2)); }c1.getName().compareTo(c2.getName())41is called to compare two thread namesThe thread::getName method reference
Overview of FunctionalInterfaces: BiFunction42
Overview of Common Functional Interfaces: BiFunction A BiFunction applies a computation on 2 parameters & returns a result, e.g., public interface BiFunction T, U, R { R apply(T t, U u); }43See on/BiFunction.html
Overview of Common Functional Interfaces: BiFunction A BiFunction applies a computation on 2 parameters & returns a result, e.g., public interface BiFunction T, U, R { R apply(T t, U u); }44See on/BiFunction.html
Overview of Common Functional Interfaces: BiFunction A BiFunction applies a computation on 2 parameters & returns a result, e.g., public interface BiFunction T, U, R { R apply(T t, U u); }Map String, Integer iqMap new ConcurrentHashMap String, Integer () {{ put("Larry", 100); put("Curly", 90); put("Moe", 110); }};Create a map of “stooges” & their IQs!for (Map.Entry String, Integer entry : iqMap.entrySet())entry.setValue(entry.getValue() - 50);vs.iqMap.replaceAll((k, v) - v - 50);45See ster/Java8/ex4
Overview of Common Functional Interfaces: BiFunction A BiFunction applies a computation on 2 parameters & returns a result, e.g., public interface BiFunction T, U, R { R apply(T t, U u); }Map String, Integer iqMap new ConcurrentHashMap String, Integer () {{ put("Larry", 100); put("Curly", 90); put("Moe", 110); }};for (Map.Entry String, Integer entry : iqMap.entrySet())entry.setValue(entry.getValue() - 50);vs.Conventional way of subtracting 50 IQ points from each person in mapiqMap.replaceAll((k, v) - v - 50);46
Overview of Common Functional Interfaces: BiFunction A BiFunction applies a computation on 2 parameters & returns a result, e.g., public interface BiFunction T, U, R { R apply(T t, U u); }Map String, Integer iqMap new ConcurrentHashMap String, Integer () {{ put("Larry", 100); put("Curly", 90); put("Moe", 110); }};for (Map.Entry String, Integer entry : iqMap.entrySet())entry.setValue(entry.getValue() - 50);vs.BiFunction lambda subtracts 50 IQ points from each person in mapiqMap.replaceAll((k, v) - v - 50);47See rent/ConcurrentHashMap.html#replaceAll
Overview of Common Functional Interfaces: BiFunction A BiFunction applies a computation on 2 parameters & returns a result, e.g., public interface BiFunction T, U, R { R apply(T t, U u); }Map String, Integer iqMap new ConcurrentHashMap String, Integer () {{ put("Larry", 100); put("Curly", 90); put("Moe", 110); }};for (Map.Entry String, Integer entry : iqMap.entrySet())entry.setValue(entry.getValue() - 50);vs.Unlike Entry operations, replaceAll() operates in a thread-safe manner!iqMap.replaceAll((k, v) - v - 50);See torial-atomic-concurrent-map-examples48
Overview of Common Functional Interfaces: BiFunction A BiFunction applies a computation on 2 parameters & returns a result, e.g., public interface BiFunction T, U, R { R apply(T t, U u); }class ConcurrentHashMap K,V {.public void replaceAll(BiFunction ? super K, ? super V, ? extends V function) {.for (Node K,V p; (p it.advance()) ! null; ) {V oldValue p.val;for (K key p.key;;) {V newValue function.apply(key, oldValue);.replaceNode(key, newValue, oldValue).49 uses the bifunction passed to itHere’s how the replaceAll() method
Overview of Common Functional Interfaces: BiFunction A BiFunction applies a computation on 2 parameters & returns a result, e.g., public interface BiFunction T, U, R { R apply(T t, U u); }class ConcurrentHashMap K,V {(k, v) - v - 50.public void replaceAll(BiFunction ? super K, ? super V, ? extends V function) {.for (Node K,V p; (p it.advance()) ! null; ) {V oldValue p.val;for (K key p.key;;) {V newValue function.apply(key, oldValue
Recognize foundational functional programming features in Java 8, e.g., Lambda expressions Method & constructor references Key functional interfaces Functional Interfaces Predicate Function Supplier Consumer BiFunction
java.io Input and output java.lang Language support java.math Arbitrary-precision numbers java.net Networking java.nio "New" (memory-mapped) I/O java.rmi Remote method invocations java.security Security support java.sql Database support java.text Internationalized formatting of text and numbers java.time Dates, time, duration, time zones, etc.
Java Version Java FAQs 2. Java Version 2.1 Used Java Version This is how you find your Java version: Start the Control Panel Java General About. 2.2 Checking Java Version Check Java version on https://www.java.com/de/download/installed.jsp. 2.3 Switching on Java Console Start Control Panel Java Advanced. The following window appears:
3. _ is a software that interprets Java bytecode. a. Java virtual machine b. Java compiler c. Java debugger d. Java API 4. Which of the following is true? a. Java uses only interpreter b. Java uses only compiler. c. Java uses both interpreter and compiler. d. None of the above. 5. A Java file with
Introduction to Functional Programming in Java 8 Java 8 is the current version of Java that was released in March, 2014. While there are many new features in Java 8, the core addition is functional programming with lambda expressions. In this section we describe the benefits of functional programming and give a few examples of the programming .
besteht aus der Java-API (Java Application Programming Interface) und der Java-VM (Java Virtual Machine). Abbildung 1: Java-Plattform Die Java-API ist eine große Sammlung von Java-Programmen, die in sog. Pakete (packages) aufgeteilt sind. Pakete sind vergleichbar mit Bibliotheken in anderen Programmiersprachen und umfassen u.a.
JAR Javadoc Java Language jar Security Others Toolkits: FX Java 2D Sound . Java Programming -Week 1. 6/25. Outline Java is. Let’s get started! The JDK The Java Sandbox . into your namespace. java.lang contains the most basic classes in the Java language. It is imported automatically, so
2 Java Applications on Oracle Database 2.1 Database Sessions Imposed on Java Applications 2-1 2.2 Execution Control of Java Applications 2-3 2.3 Java Code, Binaries, and Resources Storage 2-3 2.4 About Java Classes Loaded in the Database 2-4 2.5 Preparing Java Class Methods for Execution 2-5 2.5.1 Compiling Java Classes 2-6
The Java Platform The Java platform has two components: The Java Virtual Machine (Java VM) The Java Application Programming Interface(Java API) The Java API is a large collection of ready-made software components that provide many useful capa