JDK 8 ExpresionesLambda

Slides:



Advertisements
Presentaciones similares
Curso de java básico (scjp)
Advertisements

Lenguaje de programación Java
Tema 6: Clases Antonio J. Sierra.
Programación orientada a objetos
UNIVERSIDAD AUTÓNOMA DEL ESTADO DE HIDALGO ESCUELA SUPERIOR DE ZIMAPÁN Licenciatura en Contaduría Tema: Like, love, hate L.E.L.I. Paulina Trujillo Castillo.
What time is it? DLT: I can tell time in Spanish..
Los complementos directos Direct Object Pronouns.
POR QUÉ VS. PORQUE. ¿Por qué? = Why? *Note the accent on the letter e. * Also note that it is two separate words.
Department of Modern Languages Gramática nueva tengo tienes tiene tenemos tenéis tienen The verb tener means to have or to possess. It is an irregular.
©2014 by Vista Higher Learning, Inc. All rights reserved  You will now learn how to use the subjunctive with verbs and expressions of will and influence.
Copyright © 2008 Vista Higher Learning. All rights reserved  You will now learn how to use the subjunctive with verbs and expressions of will and.
TOPICS: SABER/CONOCER AND YO-GO VERBS Essential questions: How do I say whom and what I know? How do I use some other irregular verbs?
Regular –AR verbs.  In Spanish there are three types of regular verbs, those that end in –AR, -ER and –IR  This ending sets up a pattern for how the.
SABER VS. CONOCER TO KNOW. Saber and conocer can both be translated to the English verb: to know. But they are used in completely different situations.
Las palabras interrogativas
Adverbs are words that describe how, when, and where actions take place. They can modify verbs, adjectives, and even other adverbs. In previous lessons,
Most commonly used is QUE Means that, which, who NEVER omitted in Spanish!
decir  (yo) digo tener  (yo) tengo venir  (yo) vengo
10.4 Adverbs ANTE TODO  Adverbs are words that describe how, when, and where actions take place.  They can modify verbs, adjectives, and even other adverbs.
Los pronombres relativos que y quien El subjuntivo en cláusulas adjetivales: con antecedentes indefinidos o que no existen.
Las Horas del Día hora hora o’clock §The word hora means time in asking the time of the day. In standing time the word hora is understood. There is not.
What time is it? DLT: I can tell time in Spanish..
Programación en Java Introducción a Java. Reseña histórica Surge en 1991 por Sun Microsystems Desarrollado para electrodomésticos Se buscaba un código.
Present Tense of AR Verbs Las clases de Sra. Schwarz Realidades 1.
Affirmative and Negative Words P. 31 Realidades 2.
Lenguaje de programación: Lua Fundamentos de lenguaje de programación. Iván Cardemil Patricio Tudela Camilo Rojas Llosect Moscoso.
THE VERB ESTAR Español 1 – Unidad 2 Lección 2. THE VERB ESTAR The verb estar means TO BE and is used to indicate LOCATION as well as to say how people.
PROGRAMACIÓN ORIENTADA A OBJETOS SEGUNDA UNIDAD: “CLASES, OBJETOS Y MÉTODOS” IRVING YAIR SALAS CHÁVEZ ING. EN SISTEMAS COMPUTACIONALES - ITSLP.
The conditional tense in Spanish expresses what you would do or what would happen under certain circumstances. Copyright © 2008 Vista Higher Learning.
Taller de Java Universidad de los Andes
¿Qué son los verbos irregulares?
Los verbos con cambio radical (e—ie)
To be, or not to be? Let’s start out with one of the most important verbs in Spanish: ser, which means “to be.”
Asking Questions P. 184 Realidades 1.
The conditional tense in Spanish expresses what you would do or what would happen under certain circumstances. Copyright © 2008 Vista Higher Learning.
To be, or not to be? Let’s start out with one of the most important verbs in Spanish: ser, which means “to be.”
CONJUGATIONS TOP 10 IRREGULAR VERBS.
Las clases de Sra. Schwarz Realidades 1
PREGUNTAS: Questions and Question Words
familia, lo que (no) les gusta,
ANTE TODO Adverbs are words that describe how, when, and where actions take place. They can modify verbs, adjectives, and even other adverbs. In previous.
El subjuntivo en cláusulas adverbiales
First Grade Dual High Frequency Words
Las Palabras Interrogativas
¿Qué hora es?.
Los pronombres relativos que y quien
Demonstrative Adjectives and Pronouns
The conditional tense in Spanish expresses what you would do or what would happen under certain circumstances. Copyright © 2008 Vista Higher Learning.
Demonstrative adjectives and pronouns
PREGUNTAS: Questions and Question Words
Asking Questions P. 184 Realidades 1.
The present tense of ir and jugar
Los pronombres relativos que y quien
Quasimodo: Tienes que hacer parte D de la tarea..
¿Te gusta ir a la escuela? ¿Por qué sí o no?
Forming questions.
You will now learn how to use the subjunctive with verbs and expressions of will and influence. © by Vista Higher Learning, Inc. All rights reserved.
You will now learn how to use the subjunctive with verbs and expressions of will and influence. © by Vista Higher Learning, Inc. All rights reserved.
Asking Questions P. 184 Realidades 1.
The Present Tense of Stem-Changing Verbs: e  ie,
ANTE TODO Adverbs are words that describe how, when, and where actions take place. They can modify verbs, adjectives, and even other adverbs. In previous.
Asking Questions P. 184 Realidades 1.
Asking Questions P. 184 Realidades 1.
Las Palabras Interrogativas
You will now learn how to use the subjunctive with verbs and expressions of will and influence. © by Vista Higher Learning, Inc. All rights reserved.
Los adjetivos demostrativos Notes #16 What is a demonstrative adjective in English? Demonstrative adjectives in English are simply the words: THISTHESE.
El Subjuntivo Expressions of Doubt
Gustar, Interesar, Aburrir
Pero and sino Preview Pero and sino.
Mis clases – tarea de ayer
Transcripción de la presentación:

JDK 8 ExpresionesLambda

Objetivo: Aprender a utilizar las expresiones lambda y los flujos de Java 8

Expresiones lambda ¿Porqué Java requiere las expresiones lambda? Sintaxis de las expresiones lambda Interfaces funcionales y su definición Package java.util.function Refrencia a métodos y constructores Referenciaa variables externas Métodos útiles en el JDK 8 que pueden utilizar lambdas

Concurrencia en JAVA

Problema: Iteración externa Nuestro código controla la iteración Inherentemente es serial: itera del inicio al fin No es thread-safe

Iteración interna con INNER CLASSES La iteraciónón es controlada por la biblioteca No es inherentemente serial – transversal se podría realizar en paralelo Se podría hacer transversal de forma perezosa (lazily) Thread safe Barrera: Sintacticamente horrible

Iteración interna con expresiones lambda más legible más abstracta menos propensa a errores Nota: se requiere más trabajo para que este código compile!

Conclusión Necesidad de hacer cambios a Java para simplificar la codificación que pueda ser paralelizada Las expresiones lambda simplifican el paso de comportamiento utilizando parámetros

Sintaxis

Expresiones lambda SON Funciones Anónimas Función anónima: son semejantes a los métodos pero sin clase (parámetros) -> { cuerpo-lambda} El cuerpo de la expresión lambda puede generar excepciones Las lambdas de una única línea No necesitan llaves no requieren una instrucción de retorno explicita las lambdas con un único parámetro no requieren paréntesis lambdas sin parámetros deben tener paréntesis

Ejemplos: sintaxis expresiones lambda

Expresiones lambda: Intferencia de tipo Definición de método static<T> T process (List <T L , Comparator<T> C) Uso del método List <String> list = getList(); process (list, (String x, String y) -> x.length() – y.length()); El compilador es astuto String r = process(list, (x, y) -> x.length() –y.length())

Conclusiones La sintaxis de las expresiones lambda es sencillo Corchetes y llaves son opcionales en ciertas situaciones A menudo no es necesario indicar el tipo de la interfaz Java sigue siendo un lenguaje fuertemente tipado

Interfaces funcionales y su definición

Tipos de las expresiones lambda Una expresión lambda es una función anónima No está asociada con una clase Java es un lenguaje fuertemente tipado ¿Cúal es el tipo de una expresión lambda? Una expresion lambda puede ser utilizada en cualquier parte en donde el tipo es una interfaz funcional La expresión lambda proporciona la implementación del método abstracto

Definición de interfaz funcional Una interfaz Tiene un único método abstracto Antes de JDK 8 esto era obvio Sólo un método JDK introdujo métodos por defecto JDK 8 permite métodos estáticos en las interfaces anotación @FunctionalInterface

Interfaces funcionales

¿La siguiente función es una interfaz funcional? Sí. Sólo tiene un método abstracto

¿La siguiente función es una interfaz funcional? Sí. Sólo tiene un método abstracto

¿La siguiente función es una interfaz funcional? Por lo que sí, es una interfaz funcional. Sólo tiene un método abstracto El método equals(Object) es implícito de la clase Object

ejemplos de uso de las expresiones lambda

Conclusiones Las expresiones lambda pueden ser utilizadas en cualquier parte en donde el tipo es una interfaz funcional Una interfaz funcional tiene un único método abstracto Las expresiones lambda proporcionan la implementación de un único método abstracto de la interfaz funcional

Interfaces funcionales en el Package java.util.function

The interfaces in this package are general purpose functional interfaces used by the JDK, and are available to be used by user code as well. While they do not identify a complete set of function shapes to which lambda expressions might be adapted, they provide enough to cover common requirements. Other functional interfaces provided for specific purposes, such as FileFilter, are defined in the packages where they are used. The interfaces in this package are annotated with FunctionalInterface. This annotation is not a requirement for the compiler to recognize an interface as a functional interface, but merely an aid to capture design intent and enlist the help of the compiler in identifying accidental violations of design intent. Functional interfaces often represent abstract concepts like functions, actions, or predicates. In documenting functional interfaces, or referring to variables typed as functional interfaces, it is common to refer directly to those abstract concepts, for example using "this function" instead of "the function represented by this object". When an API method is said to accept or return a functional interface in this manner, such as "applies the provided function to...", this is understood to mean a non-nullreference to an object implementing the appropriate functional interface, unless potential nullity is explicitly specified.

The functional interfaces in this package follow an extensible naming convention, as follows: There are several basic function shapes, including Function (unary function from T to R), Consumer (unary function from Tto void), Predicate (unary function from T to boolean), and Supplier (nilary function to R). Function shapes have a natural arity based on how they are most commonly used. The basic shapes can be modified by an arity prefix to indicate a different arity, such as BiFunction (binary function from T and U to R). There are additional derived function shapes which extend the basic function shapes, including UnaryOperator (extends Function) and BinaryOperator (extends BiFunction). Type parameters of functional interfaces can be specialized to primitives with additional type prefixes. To specialize the return type for a type that has both generic return type and generic arguments, we prefix ToXxx, as in ToIntFunction. Otherwise, type arguments are specialized left-to-right, as in DoubleConsumer or ObjIntConsumer. (The type prefix Obj is used to indicate that we don't want to specialize this parameter, but want to move on to the next parameter, as in ObjIntConsumer.) These schemes can be combined, as in IntToDoubleFunction. If there are specialization prefixes for all arguments, the arity prefix may be left out (as in ObjIntConsumer).

Package java.util.pakage Bien definido conjunto de interfaces funcionales de propósito general Todas tienen un único método abstract las expresiones lambda pueden ser utilizadas en todos los lugares en donde estos tipos son referenciados ampliamente utilizados en la biblioteca de clases de Java Especialmente en la API STREAM A continuación se describen las interfaces genéricas Hay numerosas versiones para diferentes tipos Double, Int, Long y Obj

Consumer(T) Operación que toma un único valor y no devuelve resultado alguno Tambien BiConsumer<T, U> acepta 2 valores y no regresa valor alguno Contienen un método para la composición de funciones andThen(Consumer after)

Supplier Un proveedor de resultados Lo opuesto a un consumidor

function<T, R> Una función que acepta un argumento y proporciona un resultado El tipo del argumento y el del resultado pueden ser diferents Tambien la función BiFunction<T, U, R> que acepta 2 parametros y regresa un resultado métodos útiles para realizar la composición compose, and Then

UnaryOperator<T> Forma Especializada de una función Un único argumento y el resultado es del mismo tipo que el valor devuelto T apply(T a)

BinaryOperator<T> Forma especializada de BiFuncion Dos argumentos y un resultado, todos del mismo tipo T apply( T a, T b)

Predicado Toma dos argumentos Función bivaluada booleana Toma dos argumentos Proporciona métodos estáticos y por defecto útiles para la combinación and(), or(), negate(), isEqual()

Conclusiones El paquete functions proporciona una amplia gama e interfaces funcikonales Ampliamente utilizada en Streams Poco probable que necesite definir sus propias extensiones al paquete functions

Métodos y Constructor

Referencias DE método Las referencias de método nos permite reutilizar un método como una expresión lambda

Referencias de método Formato: referencia_objetivo::nombre_metodo Más detalles Formato: referencia_objetivo::nombre_metodo tres tipos de referencias de método Static method Instance method of an arbitrary type Instance method of an existing object

Referencias de método Reglas de construcción

Referencias de método Ejemplos:

Referencias de constructores Mismo concepto de referencias de método Para el constructor

Conclusiones Las referencias de método proporcionan una notación compacta para las lambdas simples Existen tres tipos dependiendo en como son utilizadas Pueden también ser utilizadas para constructores

Referenciacion a variables externas en las expresiones lambda

Captura de variable local Expresiones lambda pueden referenciar a variables locales finales del ámbito final: una variable que cumple los requerimientos de las variables Closures sobre los valores no sobre las variables

¿Qué significa this en una lambda ‘this’ se refiere al objeto envolvente, no a la misma lambda Piense en this como un “final predefined local” Recuerde que la lambda es una función anonima No esta asociada con una clase `pr lo tanto no existe un “this” para la lambda

Referenciación a variables de instancia Cuales no son finales o efectivamente finales

Referenciación a variables de instancia Las cuales no son finales o efectivamente finales ‘this’ (efectivamente final) es insertado por el compilador

Conclusiones Las variables en el ámbito circundante pueden ser utilizadas en las expresiones lambda Pero deben ser final o efectivamente final ‘this’ en una lambda se refiere al objeto del ámbito circundante el compilador insertará una referencia a ‘this’ donde sea necesario

Nuevos métodos útiles en jdk 8 que pueden utilizar lambdas

interfaz iterable

Interface Collection

Interface List

Interface List

Clase Logger

Conclusiones Utilice los nuevos métodos del JDK 8 para eliminar la necesidad de biucles Recuerde que una lambda proporciona comportamiento, no un valor Útiles para el uso condicional de datos